I am trying to write code to detect the start of a loop using Floyds cycle detection algorithm. My link list is like this
1->2->3->4->5->6
|_____|
This is the code I am using
bool findCycle(Node* root)
{
auto slow = root;
auto fast = slow->next->next;
while (slow != nullptr && fast != nullptr)
{
if (slow == fast)
{
//Yes there is a loop. Lets find the start of the loop
//Move slow to the head again and move by one pointer each.
slow = root;
while (slow != nullptr && fast != nullptr)
{
if (slow != fast)
{
slow = slow->next;
fast = fast->next;
}
else
{
std::cout << "The loop starts at node " << slow->val;
return true;
}
}
}
slow = slow->next;
fast = fast->next->next;
}
return false;
}
I have managed to detect the loop at 5. At that point I move the slow pointer to the head and keep the faster pointer at 5. Now I move each pointer by 1 and I expect them to cross at a specific node but they never cross. Is my algorithm wrong ? What am I doing wrong.