141. Linked List Cycle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast = head, slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
return true;
}
}

return false;
}
}

注意快慢指针起始位置,不要将慢指针起始位置放在快指针后,避免误判,上方解法快慢指针起始位置相同,通过先前进、后比较的方式规避了该问题。

References

141. Linked List Cycle