-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedListCycleII_142.java
50 lines (42 loc) · 1.22 KB
/
LinkedListCycleII_142.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
/**
* Two pointers 1 step; 2 step
* x + y = k -- x: start to cycle start
* -- y: cycle start to first meet
* -- k: the k steps of the first pointer
* x + y + nt = 2k -- t: length of the cycle
* -- n: n cycles
* -- 2k:2k steps of the second pointer
* => nt = k => nt - y = k - y = x
* one pointer k steps ahead, and the other from the start
* each one step each time
* the first time they meet
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null) return null;
ListNode p1 = head, p2 = head;
while(p2 != null && p2.next != null) {
p1 = p1.next;
p2 = p2.next.next;
if (p1 == p2) break;
}
if (p2 == null || p2.next == null) return null;
// p1's position is k step
p2 = head;
while(p2 != p1) {
p2 = p2.next; p1 = p1.next;
}
return p1;
}
}