-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDetectAndRemoveLoop.java
More file actions
89 lines (74 loc) · 2.35 KB
/
Copy pathDetectAndRemoveLoop.java
File metadata and controls
89 lines (74 loc) · 2.35 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package LinkedList;
/**
* Created by rmukherj on 7/17/16.
*/
public class DetectAndRemoveLoop {
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;
}
private void removeloop(Node loop, Node curr) {
Node ptr1= null, ptr2=null;
/* Set a pointer to the beging of the Linked List and
move it one by one to find the first node which is
part of the Linked List */
ptr1= curr;
while(1==1){
/* Now start a pointer from loop_node and check if it ever
reaches ptr2 */
ptr2 = loop;
while (ptr2.next != loop && ptr2.next != ptr1) {
ptr2 = ptr2.next;
}
/* If ptr2 reahced ptr1 then there is a loop. So break the
loop */
if (ptr2.next == ptr1) {
break;
}
/* If ptr2 did't reach ptr1 then try the next node after ptr1 */
ptr1 = ptr1.next;
}
/* After the end of loop ptr2 is the last node of the loop. So
make next of ptr2 as NULL */
ptr2.next = null;
}
// Function to print the linked list
void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
// Driver program to test above functions
public static void main(String[] args) {
DetectAndRemoveLoop list = new DetectAndRemoveLoop();
list.head = new Node(50);
list.head.next = new Node(20);
list.head.next.next = new Node(15);
list.head.next.next.next = new Node(4);
list.head.next.next.next.next = new Node(10);
// Creating a loop for testing
list.printList(head);
head.next.next.next= head.next.next;
list.detectAndRemoveLoop(head);
System.out.println("Linked List after removing loop : ");
list.printList(head);
}
}