forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemovalofCycleinLinkedList.cpp
87 lines (86 loc) · 1.43 KB
/
RemovalofCycleinLinkedList.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
Node(int val){
data = val;
next = NULL;
}
};
void InsertAtHead(Node *&head,int val){
if(head==NULL){
head = new Node(val);
return;
}
Node *n = new Node(val);
n->next = head;
head = n;
}
Node * Input(){
Node * head = NULL;
int d;
cin>>d;
while(d!=-1){
InsertAtHead(head,d);
cin>>d;
}
return head;
}
void PrintLL(Node *head){
while(head!=NULL){
cout<<head->data<<"->";
head = head->next;
}
cout<<"NULL"<<endl;
}
void makecycle(Node *head,int pos){
Node * temp = head;
Node * loop = NULL;
int count=1;
while(temp->next!=NULL){
if(count==pos){
loop = temp;
}
temp = temp->next;
count++;
}
temp->next = loop;
}
void RemoveCycle(Node *head){
Node *slow = head;
Node *fast = head;
while(fast->next!=NULL && fast->next->next!=NULL){
slow = slow->next;
fast = fast->next->next;
if(slow==fast){
break;
}
}
//if loop starts at first node
if(fast==head){
while(slow->next!=fast){
slow=slow->next;
}
slow->next = NULL;
return;
}
//Meeting at starting point of cycle
fast = head;
while(fast->next!=slow->next){
fast = fast->next;
slow = slow->next;
}
slow->next = NULL;
}
int main(){
Node *head = Input();
PrintLL(head);
int pos;
cin>>pos;
makecycle(head,pos);
RemoveCycle(head);
PrintLL(head);
}