-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathdetectionOfCycle_linkedList.cpp
111 lines (99 loc) · 2.09 KB
/
detectionOfCycle_linkedList.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/*Below is the code which is used to find whether a cycle is present in a linked list.
It uses 2 pointer slow and fast(which travels at speed twice that of slow).
If they meet at any position while traversing the linked list then a cycle is
present otherwise cycle is not present */
#include <bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node* next;
node(int d){
data = d;
next = NULL;
}
};
void insertAtHead(node* &head,int d){
if(head==NULL){
head = new node(d);
return;
}
node* n = new node(d);
n->next = head;
head = n;
return;
}
void insertAtTail(node* &head,int d){
if(head==NULL){
insertAtHead(head,d);
return;
}
node* tail = head;
while(tail->next!=NULL){
tail=tail->next;
}
tail->next = new node(d);
return;
}
void makeCycle(node* &head,int pos){
node* temp = head;
node* startNode;
int count = 1;
while(temp->next != NULL){
if(count == pos){
startNode = temp;
}
temp = temp->next;
count++;
}
temp->next = startNode;
}
bool detectCycle(node* head){
node* slow = head;
node* fast = head;
while(fast!=NULL and fast->next!=NULL){
fast = fast->next->next;
slow = slow->next;
if(fast==slow){
return true;
}
}
return false;
}
int main()
{
node* head = NULL;
int n;
cout<<"Enter the number of nodes:"<<endl;
cin>>n;
for(int i=0;i<n;i++){
int x;
cin>>x;
insertAtTail(head,x);
}
int pos;
cout<<"Enter the position where you want to make a cycle:"<<endl;
cin>>pos;
//cycle is created at position pos
makeCycle(head,pos);
//detect a cycle
if(detectCycle(head)){
cout<<"Cycle is present"<<endl;
}
else{
cout<<"Cycle is not present"<<endl;
}
return 0;
}
/*
SAMPLE INPUT
7
1 2 3 4 5 6 7
3
SAMPLE OUTPUT
Enter the number of nodes:
Enter the position where you want to make a cycle:
Cycle is present
Time Complexity O(N)
Space Complexity O(1)
*/