bool ListContainsLoop(node * head)
{
node * slowPtr = head;
node * fastPtr = head;
while(slowPtr && fastPtr)
{
fastPtr = fastPtr->link; // advance the fast pointer
if(fastPtr == slowPtr) // and check if its equal to the slow pointer
return true; // loop detected
if(fastPtr == NULL)
{
return false; // since fastPtr is NULL we reached the tail
}
fastPtr = fastPtr->link; //advance and check again
if(fastPtr == slowPtr)
return true;
slowPtr = slowPtr->link; // advance the slow pointer only once
}
return false; // we reach here if we reach the tail
}
No comments:
Post a Comment