-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloop_LinkedList.java
More file actions
67 lines (57 loc) · 1.67 KB
/
Copy pathloop_LinkedList.java
File metadata and controls
67 lines (57 loc) · 1.67 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
// Java program to detetct loop in a linked list and remove it.
class loop_LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
int detectAndRemoveLoop(Node node) {
Node slow = node, fast = node;
while (slow != null && fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
removeLoop(slow, node);
return 1;
}
}
return 0;
}
void removeLoop(Node loop, Node curr) {
Node ptr1 = null, ptr2 = null;
ptr1 = curr;
while (1 == 1) {
ptr2 = loop;
while (ptr2.next != loop && ptr2.next != ptr1) {
ptr2 = ptr2.next;
}
if (ptr2.next == ptr1) {
break;
}
ptr1 = ptr1.next;
}
ptr2.next = null;
}
void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public static void main(String[] args) {
loop_LinkedList list = new loop_LinkedList();
list.head = new Node(50);
list.head.next = new Node(20);
list.head.next.next = new Node(16);
list.head.next.next.next = new Node(8);
list.head.next.next.next.next = new Node(10);
head.next.next.next.next.next = head.next.next;
list.detectAndRemoveLoop(head);
System.out.println("Linked List after removing loop : ");
list.printList(head);
}
}