-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListCycleII.java
More file actions
75 lines (66 loc) · 1.65 KB
/
LinkedListCycleII.java
File metadata and controls
75 lines (66 loc) · 1.65 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package leetcode;
import utils.ListNode;
import utils.Lists;
/**
* LinkedListCycleII
* https://leetcode-cn.com/problems/linked-list-cycle-ii/
*
* @since 2020-10-10
*/
public class LinkedListCycleII {
public static void main(String[] args) {
ListNode head = Lists.fromInts(new int[]{3, 2, 0, -4}, 1);
LinkedListCycleII sol = new LinkedListCycleII();
ListNode res = sol.detectCycle(head);
if (res == null) {
System.out.println("no cycle");
} else {
System.out.println("tail connects to node " + res.val);
}
}
public ListNode detectCycle(ListNode head) {
if (head == null) {
return null;
}
ListNode fast = head;
ListNode slow = head;
int dist = 0;
while (true) {
if (fast.next != null) {
fast = fast.next;
} else {
dist = -1;
break;
}
if (fast == slow) {
dist++;
break;
}
if (fast.next != null) {
fast = fast.next;
} else {
dist = -1;
break;
}
if (fast == slow) {
dist += 2;
break;
}
slow = slow.next;
dist++;
}
if (dist == -1) {
return null;
}
slow = head;
fast = head;
for (int i = 0; i < dist; i++) {
fast = fast.next;
}
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}