-
Notifications
You must be signed in to change notification settings - Fork 0
/
142. Linked List Cycle II
54 lines (47 loc) · 1.21 KB
/
142. Linked List Cycle II
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
51
52
53
54
/*
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
*/
/*
Idea:
x - head to entry point;
y - meating point to entry point;
s - cycle length;
x
0-0-e.p.-0-0-0-0
| |
0-0-m-0-0-0
t slow = t fast => (x + (S-y)) / 1 = (x + S + (S - y)) / 2 <=> 2x + 2S + 2y = x +2S - y <=> x = y
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null) {
return null;
}
ListNode slow = head.next;
ListNode fast = head.next == null ? null : head.next.next;
while (slow != null && fast != null) {
if (slow == fast) {
ListNode slowFromHead = head;
while (slow != slowFromHead) {
slow = slow.next;
slowFromHead = slowFromHead.next;
}
return slowFromHead;
}
slow = slow.next;
fast = fast.next == null ? null : fast.next.next;
}
return null;
}
}
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/