-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart_point_of_loop_in_linked_list.cpp
More file actions
66 lines (55 loc) · 1.32 KB
/
Copy pathstart_point_of_loop_in_linked_list.cpp
File metadata and controls
66 lines (55 loc) · 1.32 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
//finding starting point of loop in LL
//https://ide.geeksforgeeks.org/srPsOYSEEm
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
struct Node* next;
};
void printLL(struct Node* head){
while(head != NULL){
cout<<head->data<<"\t";
head = head->next;
}
cout<<"\n";
}
Node* newNode(int key)
{
Node* temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
}
struct Node* findAndDetectLoop(struct Node* head){
struct Node* fast = head;
struct Node* slow = head;
slow = slow->next;
fast = fast->next->next;
while(fast && fast->next){
if(slow == fast){
break;
}
slow = slow->next;
fast = fast->next->next;
}
if (slow != fast)
return NULL;
slow = head;
while(slow != fast){
slow = slow->next;
fast = fast->next;
}
return slow;
}
int main()
{
Node* head = newNode(50);
head->next = newNode(20);
head->next->next = newNode(15);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(10);
head->next->next->next->next->next = head->next->next; //loop
Node* find = findAndDetectLoop(head);
cout<<"Starting point of loop is: "<<find->data<<"\n";
return 0;
}