-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemove loop in Linked List
More file actions
42 lines (39 loc) · 1.05 KB
/
Remove loop in Linked List
File metadata and controls
42 lines (39 loc) · 1.05 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
/*
class Node
{
int data;
Node next;
}
*/
class Solution {
// Function to remove a loop in the linked list.
public static void removeLoop(Node head) {
Node slow = head;
Node fast = head;
// Detect loop
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
// Loop detected
if (slow == fast) {
// Find start of loop
slow = head;
if (slow == fast) {
// Special case: loop starts at head
while (fast.next != slow) {
fast = fast.next;
}
fast.next = null;
} else {
while (slow.next != fast.next) {
slow = slow.next;
fast = fast.next;
}
// Break the loop
fast.next = null;
}
return;
}
}
}
}