Skip to content

Commit d345077

Browse files
authored
Circular Linked List
1 parent 9db7ee4 commit d345077

File tree

1 file changed

+110
-0
lines changed

1 file changed

+110
-0
lines changed
+110
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
/* Leet Code */
2+
/* Title - Circular Linked List */
3+
/* Created By - Akash Modak */
4+
/* Date - 2/8/2020 */
5+
6+
// We are given a linked list which contains a cycle. Detect that cycle and break it. Print the linked list after removing the cycle.
7+
8+
// Input Format
9+
// The first line contains space separated integers. The integers are such that all the values are distinct but the value start repeating once the cycle gets completed. The list of integers given ends when -1 is input.
10+
11+
// Constraints
12+
// n < 10^5 where n is the length of list without the cycle
13+
14+
// Output Format
15+
// Output single line containing space separated integers representing the list
16+
17+
// Sample Input
18+
// 1 2 3 4 5 2 3 -1
19+
// Sample Output
20+
// 1 2 3 4 5
21+
// Explanation
22+
// Initially the first five elements are unique but starts repeating from 2. This means there is a link from 5 back to 2. So it represents a cycle. We have to break this cycle and print the list after breaking the cycle.
23+
24+
#include<iostream>
25+
using namespace std;
26+
bool cycle = false;
27+
class Node{
28+
public:
29+
int data;
30+
Node* next;
31+
Node(int d){
32+
data=d;
33+
next = NULL;
34+
}
35+
};
36+
Node* addNode(Node* head,Node* add){
37+
if(head==NULL){
38+
39+
head = add;
40+
return head;
41+
}
42+
Node* temp = head;
43+
Node* save;
44+
while(temp->next!=NULL){
45+
if(temp->data==add->data){
46+
save = temp;
47+
cycle=true;
48+
}
49+
temp=temp->next;
50+
}
51+
if(cycle){
52+
temp->next=save;
53+
}
54+
else{
55+
temp->next = add;
56+
}
57+
return head;
58+
}
59+
void inp(Node* &head){
60+
int d;
61+
while(cin>>d && d!=-1){
62+
if(cycle){
63+
break;
64+
}
65+
Node* temp = new Node(d);
66+
head = addNode(head,temp);
67+
}
68+
}
69+
Node* detectCycle(Node* head){
70+
Node* slow = head;
71+
Node* fast = head;
72+
73+
while(fast!=NULL && fast->next!=NULL){
74+
slow = slow->next;
75+
fast = fast->next->next;
76+
if(slow==fast)
77+
break;
78+
}
79+
return fast;
80+
}
81+
void breakCycle(Node*&head){
82+
Node* fast = detectCycle(head);
83+
if(fast==head){
84+
Node*temp = head->next;
85+
while(temp->next!=head)
86+
temp=temp->next;
87+
temp->next=NULL;
88+
return;
89+
}
90+
Node* prev = fast;
91+
Node* slow = head;
92+
if(cycle){
93+
while(slow!=fast){
94+
slow=slow->next;
95+
prev = fast;
96+
fast = fast->next;
97+
}
98+
prev ->next = NULL;
99+
}
100+
}
101+
int main() {
102+
Node* head = NULL;
103+
inp(head);
104+
breakCycle(head);
105+
while(head!=NULL){
106+
cout<<head->data<<" ";
107+
head=head->next;
108+
}
109+
return 0;
110+
}

0 commit comments

Comments
 (0)