-
Notifications
You must be signed in to change notification settings - Fork 0
/
findLoopLength.cpp
60 lines (51 loc) · 1.25 KB
/
findLoopLength.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
#include "../headers/LinkedList.h"
using namespace std;
/**
* This method finds the length of the loop present in the link list
* Uses Floyd's cycle-finding algorithm
*
* @link Floyd's cycle-finding algorithm https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_Tortoise_and_Hare
* @link GFG:Detect loop in a linked list https://www.geeksforgeeks.org/detect-loop-in-a-linked-list/
* @param head Node class pointer pointing head of linked list
* @return int Length of the loop
*/
int findLoopLength(Node* head){
// Detect Loop
Node* slowPtr = head;
Node* fastPtr = head;
Node* loopNode = NULL;
int loopLength = 0;
while(fastPtr!=NULL && fastPtr->next!=NULL){
slowPtr = slowPtr->next;
fastPtr = fastPtr->next->next;
if(slowPtr==fastPtr){
loopNode = slowPtr;
break;
}
}
// Find length of loop
if(loopNode!=NULL){
do
{
++loopLength;
slowPtr = slowPtr->next;
} while (loopNode!=slowPtr);
}
return loopLength;
}
int main()
{
Node* n1 = new Node(1);
Node* n2 = new Node(2);
Node* n3 = new Node(4);
Node* n4 = new Node(5);
Node* n5 = new Node(8);
n1->next = n2;
n2->next = n3;
n3->next = n4;
n4->next = n5;
n5->next = n2;
cout<<findLoopLength(n1);
delete n1,n2,n3,n4,n5;
return 0;
}