i want to know that why we use two conditions i am confused.. while head and head->next are not equal to null which means head and head's next will point to null ho is that possible
int detectCycle(Node *& head)
{
Node * fast = head;
Node * slow = head;
while(fast!=nullptr && fast->next!=nullptr) // i am confused in these two conditions
{
slow = slow->next;
fast = fast->next->next;
if(fast == slow)
return 1;
}
return false;
}
From the code presented, I guess you mean
fastwhere you wrotehead.If
fastis null thenfast!=nullptrevaluates to false. In that case it would produce undefined behavior to evaluatefast->next, but that is not an issue because the&&operator has short-circuiting behavior. That is, if the left operand of an&&operator evaluates to false, then the right operand is not evaluated.Thus the
whilecondition is safe to evaluate, and it evaluates to true if and only if neitherfastnorfast->nextis a null pointer.Supposing that
headis a pointer to the head node of a linked list, the code seems to assume that the last node can be recognized by having anextpointer whose value is null. This is a very common paradigm, so it is absolutely reasonable to think that as thefastpointer is advanced through the list (two links at a time), it will eventually become the case that either it or its successor will be the last node, and therefore have a nullnextpointer.If that happens, then the list is proven not to loop. If the list does loop, however, then it will eventually be the case that
slow, which advances only one link at a time instead of two, will point to the same node thatfastdoes. When that is detected, the list is known to loop.