-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathListCycle.java
More file actions
68 lines (55 loc) · 1.79 KB
/
ListCycle.java
File metadata and controls
68 lines (55 loc) · 1.79 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
package LinkedLists;
public class ListCycle {
public static boolean hasCycle(Node head) {
Node fast = head;
Node slow = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (fast == slow) return true;
}
return false;
}
/**
* x denotes the length of the linked list before starting the cycle.
* y denotes the distance from the start of the cycle to where slow and fast met.
* C denotes the length of the cycle
* when they meet, slow traveled (x + y) steps while fast traveled 2 * (x + y) steps, and the extra distance (x + y) must be a multiple of the circle length C
*/
public static Node detectCycle(Node head) {
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (fast == slow) break;
}
if (fast == null || fast.next == null) return null;
while (head != slow) {
head = head.next;
slow = slow.next;
}
return slow;
}
public static void removeLoop(Node head) {
Node fast = head;
Node slow = head;
Node prev = fast;
while (fast != null && fast.next != null) {
// This because if they meet at the head.
prev = fast.next;
slow = slow.next;
fast = fast.next.next;
if (fast == slow) break;
}
if (fast == null || fast.next == null) return;
while (fast != head) {
prev = fast;
fast = fast.next;
head = head.next;
}
prev.next = null;
}
public static void main(String[] args) {
}
}