Skip to content

Commit 6f2bc7a

Browse files
saumyashrm2802jainaman224
authored andcommitted
[Re] Added Detecting and Removing Cycle from a linked list (jainaman224#1047)
1 parent cc4bbd4 commit 6f2bc7a

File tree

1 file changed

+108
-0
lines changed

1 file changed

+108
-0
lines changed
+108
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
/*
2+
Technique used:
3+
4+
This method of detecting cycle is dependent upon Floyd's Cycle Detection Algorithm.
5+
In Floyd's Cycle Detection Algorithm, we take two pointers : fast and slow.
6+
The algorithm comes to an end when both of these pointers meet at a common point.
7+
Then, we store the address of the common point in a pointer variable (temp here).
8+
We start form the head of the linked list, and check each node if it is reachable
9+
from temp. That particular node, if found, is the starting node of the linked list.
10+
We assign a pointer to the previous one of this node.
11+
*/
12+
13+
#include<iostream>
14+
using namespace std;
15+
16+
struct node
17+
{
18+
int info;
19+
node *next;
20+
};
21+
22+
//creating a new node
23+
node *create (int x)
24+
{
25+
node *ptr = new node;
26+
ptr->info = x;
27+
ptr->next = NULL;
28+
return ptr;
29+
}
30+
31+
//printing the linked list
32+
void print (node * ptr)
33+
{
34+
while (ptr != NULL)
35+
{
36+
cout << ptr->info << " ";
37+
ptr = ptr->next;
38+
}
39+
cout << "\n\n";
40+
}
41+
42+
//removing the cycle from the linked list
43+
void rem (node * slow_ptr, node * head)
44+
{
45+
node *ptr;
46+
node *temp;
47+
ptr = head;
48+
while (1)
49+
{
50+
temp = slow_ptr;
51+
while (temp->next != slow_ptr && temp->next != ptr)
52+
{
53+
temp = temp->next;
54+
}
55+
if (temp->next == ptr)
56+
break;
57+
ptr = ptr->next;
58+
}
59+
temp->next = NULL;
60+
}
61+
62+
//detecting cycle in the linked list
63+
int detect (node * ptr)
64+
{
65+
node *slow_ptr = ptr;
66+
node *fast_ptr = ptr;
67+
while (slow_ptr && fast_ptr && fast_ptr->next)
68+
{
69+
slow_ptr = slow_ptr->next;
70+
fast_ptr = fast_ptr->next->next;
71+
if (slow_ptr == fast_ptr)
72+
{
73+
//remove function called
74+
rem (slow_ptr, ptr);
75+
return 1;
76+
}
77+
}
78+
return 0;
79+
}
80+
81+
int main ()
82+
{
83+
node *head = create (10);
84+
head->next = create (20);
85+
head->next->next = create (30);
86+
head->next->next->next = head;
87+
//detect function called
88+
if (detect (head) == 1)
89+
{
90+
cout << "\nA cycle is present in the linked list\n";
91+
cout << "\n\nAfter removing the cycle, linked list is as follows:\n";
92+
//print function called
93+
print (head);
94+
}
95+
else
96+
cout << "No cycle is present within the loop\n";
97+
return 0;
98+
}
99+
100+
/* Sample input :HARDCORED VALUES:
101+
10->20->30->(attached to head)
102+
103+
Sample output:
104+
A cycle is present in the linked list
105+
106+
After removing the cycle, linked list is as follows:
107+
10 20 30
108+
/*

0 commit comments

Comments
 (0)