-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind_and_remove_loop_in_linked_list.cpp
65 lines (55 loc) · 1.27 KB
/
find_and_remove_loop_in_linked_list.cpp
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
//finding and remove loop in LL
//https://ide.geeksforgeeks.org/KhlNf75cDP
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
struct Node* next;
};
void printLL(struct Node* head){
while(head != NULL){
cout<<head->data<<"\t";
head = head->next;
}
cout<<"\n";
}
Node* newNode(int key)
{
Node* temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
}
void findAndRemoveLoop(struct Node* head){
struct Node* fast = head;
struct Node* slow = head;
slow = slow->next;
fast = fast->next->next;
while(fast && fast->next){
if(slow == fast){
break;
}
slow = slow->next;
fast = fast->next->next;
}
if (slow == fast){
slow = head;
while(slow->next != fast->next){
slow = slow->next;
fast = fast->next;
}
fast->next = NULL;
}
}
int main()
{
Node* head = newNode(50);
head->next = newNode(20);
head->next->next = newNode(15);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(10);
head->next->next->next->next->next = head->next->next; //loop
findAndRemoveLoop(head);
printLL(head);
return 0;
}