链表双指针

难度简单

题目描述

image.png

解题思路

快慢指针

Code

  1. class ListNode {
  2. int val;
  3. ListNode next;
  4. ListNode(int x) {
  5. val = x;
  6. next = null;
  7. }
  8. }
  9. public boolean hasCycle(ListNode head) {
  10. if (head == null || head.next == null) {
  11. return false;
  12. }
  13. ListNode slow = head, fast = head;
  14. boolean flag = false;
  15. while (slow != null && fast != null && fast.next != null) {
  16. slow = slow.next;
  17. fast = fast.next.next;
  18. if (slow == fast) {
  19. flag = true;
  20. break;
  21. }
  22. }
  23. return flag;
  24. }