forked from zapellass123/OpenEmailGenerator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStartingPointOfLoopInLL.cpp
More file actions
89 lines (77 loc) · 1.8 KB
/
StartingPointOfLoopInLL.cpp
File metadata and controls
89 lines (77 loc) · 1.8 KB
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
#include<bits/stdc++.h>
using namespace std;
class node {
public:
int num;
node* next;
node(int val) {
num = val;
next = NULL;
}
};
void insertNode(node* &head,int val) {
node* newNode = new node(val);
if(head == NULL) {
head = newNode;
return;
}
node* temp = head;
while(temp->next != NULL) temp = temp->next;
temp->next = newNode;
return;
}
void createCycle(node* &head,int pos) {
node* ptr = head;
node* temp = head;
int cnt = 0;
while(temp->next != NULL) {
if(cnt != pos) {
++cnt;
ptr = ptr->next;
}
temp = temp->next;
}
temp->next = ptr;
}
//process as per mentioned in solution
node* detectCycle(node* head) {
if(head == NULL||head->next == NULL) return NULL;
node* fast = head;
node* slow = head;
node* entry = head;
while(fast->next != NULL&&fast->next->next != NULL) {
slow = slow->next;
fast = fast->next->next;
if(slow == fast) {
while(slow != entry) {
slow = slow->next;
entry = entry->next;
}
return slow;
}
}
return NULL;
}
int main() {
node* head = NULL;
insertNode(head,1);
insertNode(head,2);
insertNode(head,3);
insertNode(head,4);
insertNode(head,3);
insertNode(head,6);
insertNode(head,10);
createCycle(head,2);
node* nodeRecieve = detectCycle(head);
if(nodeRecieve == NULL) cout<<"No cycle";
else {
node* temp = head;
int pos = 0;
while(temp!=nodeRecieve) {
++pos;
temp = temp->next;
}
cout<<"Tail connects at pos "<<pos<<endl;
}
return 0;
}