I have the following code in C that tries to find if a list is cyclic or not:
bool findCircular(Node *head)
{
Node *slower, * faster;
slower = head;
faster = head;
while(true) {
// if the faster pointer encounters a NULL element
if( !faster || !faster->next)
return false;
//if faster pointer ever equals slower or faster's next
//pointer is ever equal to slow then it's a circular list
else if (faster == slower || faster->next == slower)
return true;
else{
// advance the pointers
slower = slower->next;
faster = faster->next->next;
}
}
}
I have some questions regarding some parts of it. Fristly, in the first time we enter the while loop, aren't we always going to reach the condition (faster == slower)? We have initialized both faster and slower to point to the same where it points head.
And secondly, why do we want to compare also if (faster->next == slower), don't we have enough with just faster == slower
?