-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGet starting node of CLL.cpp
93 lines (76 loc) · 1.76 KB
/
Get starting node of CLL.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
#include<iostream>
#include<map>
#include "LL.cpp"
using namespace std;
/*
Using Floyds cycle detection method(slow is increased by one step and first by
2 steps) return the starting node of the loop
*/
bool isLoopPresent(Node* head){
if(head==NULL){
return false;
}
Node* slow = head;
Node* fast = head;
while(slow!=NULL and fast!=NULL){
slow = slow->next;
fast = fast->next;
if(fast!=NULL){
fast = fast->next;
}
if(slow==fast){
return true;
}
}
return false;
}
Node* getLoopNode(Node* head){
// Get starting node of the loop
if(isLoopPresent(head)){
map<Node*,bool> visited;
Node* temp = head;
while(temp){
if(visited[temp]==true){
return temp; // This is the beginning of the loop
}
visited[temp] = true;
temp = temp->next;
}
}
return NULL;
}
void makeCircular(Node* &head ,int start,int stop){
Node* ptr1 = head;
Node* ptr2 = head;
for(int i=0;i<start;i++){
ptr1 = ptr1->next;
}
for(int i=0;i<stop;i++){
ptr2 = ptr2->next;
}
ptr2->next = ptr1;
}
void printCircular(Node* head){
Node* temp = head;
for(int i=1;i<=15;i++){
cout << temp->data << "->";
temp = temp->next;
}
cout<< endl;
}
int main(){
LinkedList ll;
for(int i=1;i<=7;i++){
ll.insertEnd(i);
}
ll.display();
makeCircular(ll.head,2,6);
printCircular(ll.head);
if(getLoopNode(ll.head)!=NULL){
cout <<"Loop starts at element : "<< getLoopNode(ll.head)->data << endl;
}
else{
cout << "No loop exists in given linked list\n";
}
return 0;
}