Star

LeetCode 142. Linked List CycleII

Question

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up: Can you solve it without using extra space?

Explanation

和上面一道题不一样的地方就是要输出从哪里开始。真的是不看答案想不出来..贴一个我觉得比较清楚的讲解吧: Reference:https://discuss.leetcode.com/topic/27868/concise-java-solution-based-on-slow-fast-pointers

1
2
3
4
5
6
7
8
9
10
Definitions:
Cycle = length of the cycle, if exists.
C is the beginning of Cycle, S is the distance of slow pointer from C when slow pointer meets fast pointer.
Distance(slow) = C + S, Distance(fast) = 2 * Distance(slow) = 2 * (C + S). To let slow poiner meets fast pointer, only if fast pointer run 1 cycle more than slow pointer. Distance(fast) - Distance(slow) = Cycle
=> 2 * (C + S) - (C + S) = Cycle
=> C + S = Cycle
=> C = Cycle - S
=> This means if slow pointer runs (Cycle - S) more, it will reaches C. So at this time, if there's another point2 running from head
=> After C distance, point2 will meet slow pointer at C, where is the beginning of the cycle.

Code

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