Skip to content

Commit 6044c7e

Browse files
authored
Merge pull request #742 from XMadhur/main
Find length of Loop.cpp
2 parents d21ba27 + 3e93b1f commit 6044c7e

File tree

1 file changed

+107
-0
lines changed

1 file changed

+107
-0
lines changed

Find length of Loop.cpp

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
struct Node
5+
{
6+
int data;
7+
Node* next;
8+
9+
Node(int val)
10+
{
11+
data = val;
12+
next = NULL;
13+
}
14+
};
15+
16+
void loopHere(Node* head, Node* tail, int position)
17+
{
18+
if(position==0) return;
19+
20+
Node* walk = head;
21+
for(int i=1; i<position; i++)
22+
walk = walk->next;
23+
tail->next = walk;
24+
}
25+
26+
int countNodesinLoop(Node* head);
27+
28+
int main()
29+
{
30+
int t;
31+
cin>>t;
32+
while(t--)
33+
{
34+
int n, num;
35+
cin>>n;
36+
37+
Node *head, *tail;
38+
cin>> num;
39+
head = tail = new Node(num);
40+
41+
for(int i=0 ; i<n-1 ; i++)
42+
{
43+
cin>> num;
44+
tail->next = new Node(num);
45+
tail = tail->next;
46+
}
47+
48+
int pos;
49+
cin>> pos;
50+
loopHere(head,tail,pos);
51+
52+
cout<< countNodesinLoop(head) << endl;
53+
}
54+
return 0;
55+
}
56+
// } Driver Code Ends
57+
58+
59+
/*
60+
61+
struct Node {
62+
int data;
63+
struct Node *next;
64+
Node(int x) {
65+
data = x;
66+
next = NULL;
67+
}
68+
};
69+
70+
*/
71+
72+
// Your task is to complete the function this function
73+
// function should return the size of the loop
74+
75+
int count(struct Node *slow)
76+
{
77+
int count=1;
78+
struct Node *temp=slow;
79+
while(temp->next!=slow)
80+
{
81+
count++;
82+
temp=temp->next;
83+
}
84+
return count;
85+
}
86+
87+
int countNodesinLoop(struct Node *head)
88+
{
89+
90+
if(head==NULL || head->next==NULL)
91+
{
92+
return -1;
93+
}
94+
Node *slow=head;
95+
Node *fast=head;
96+
while (fast!=NULL && fast->next!=NULL)
97+
{
98+
slow=slow->next;
99+
fast=fast->next->next;
100+
if(slow==fast)
101+
{
102+
return count(slow);
103+
}
104+
105+
}
106+
return 0;
107+
}

0 commit comments

Comments
 (0)