Linked List Cycle II
Link: https://leetcode.com/problems/linked-list-cycle-ii/
Idea
If there's a cyle, we have the following findings:

Here 'a' means the distance from head to entry point of the cycle. Node with value 1 is the point where the slow and fast pointer first meet. Its distance to the entry point (node 0) is b, while 'c' is the distance to node 0 via the other path. Since we get a = b, if we have one pointer to start from 3, and the other pointer starts from 1, they will meet at node 0 if they both move one node at a time.
Code
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
boolean hasCycle = false;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
hasCycle = true;
break;
}
}
if (!hasCycle) {
return null;
}
slow = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
Refercnne: https://www.jiuzhang.com/problem/linked-list-cycle-ii/
浙公网安备 33010602011771号