forked from ashoklathwal/Code-for-Interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
detectCycleLinkedList.java
72 lines (71 loc) · 1.75 KB
/
detectCycleLinkedList.java
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
// Java program to detect and remove loop in linked list
class LinkedList
{
static Node head;
static class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
// Function that detects loop in the list
void detectAndRemoveLoop(Node node)
{
if(node==null || node.next==null)
return;
if(node.next==node)
{
node.next=null;
return;
}
Node slow = node;
Node fast = node.next;
// Search for loop using slow and fast pointers
while (slow != null && slow.next != null && fast != null && fast.next != null && fast.next.next != null)
{
if (slow == fast) {
break;
}
slow = slow.next;
fast = fast.next.next;
}
/* If loop exists */
if (slow == fast)
{
slow = node;
// odd or even
while (slow != fast.next && slow.next != fast.next) {
slow = slow.next;
fast = fast.next;
}
/* since fast->next is the looping point */
fast.next = null; /* remove loop */
}
}
// 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)
{
LinkedList list = new LinkedList();
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
head.next.next.next.next.next = head.next.next;
list.detectAndRemoveLoop(head);
System.out.println("Linked List after removing loop : ");
list.printList(head);
}
}