My issue
Please explain me what’s wrong with my code.
I’m getting runtime error SIGABRT.
sol: sol.cpp:73: int main(): Assertion `connection<n' failed.
My code
int solve(Node* head){
if(!head){
return -1;
}
if(!head->next){
return -1;
}
Node* slow = head;
Node* fast = head;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if(slow==fast){
int count=1;
slow=slow->next;
while(slow!=fast){
slow=slow->next;
count++;
}
return count;
}
}
return -1;
}
Learning course: Linked Lists
Problem Link: Count loop length in Linked List Practice Problem in - CodeChef
In addition, I am doing exactly what the solution explanation is saying. Please take a look at solution explanation as well:
Explanation
We can use Floyd’s Cycle-Finding Algorithm,
Here’s how you can implement and use the algorithm to find the number of elements in the loop:
- Initialize two pointers, slow and fast.
- Move the slow pointer by one step and the fast pointer by two steps in each iteration.
- If the linked list contains a cycle, the fast pointer will eventually meet the slow pointer within the cycle.
- Once the two pointers meet, keep the fast pointer where it is, and move the slow pointer one step at a time until it meets the fast pointer again. While moving the slow pointer, count the number of nodes you have traversed.
- The count at which the slow pointer meets the fast pointer again is the number of elements in the loop.
@dpcoder_007 bro do you know where the issue is? I still don’t understand this one, or maybe I should assume that this is an issue with the rest of the implemented code behind that is not visible to me
@b_suvonov
actually its a pro level course so won’t be able to open the problem .
Same question is on gfg. I Have coded it and got ac.
plzz refer it for better understanding .
int countNodesinLoop(struct Node *head)
{
// Code here
if(!head)
return 0;
if(!head->next)
return 0;
Node* slow = head;
Node* fast = head;
int cnt=0;
while(fast&&fast->next)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
{
slow=slow->next;
fast=fast->next->next;
cnt++;
while(fast!=slow)
{
cnt++;
fast=fast->next;
}
break;
}
}
return cnt;
}