Reputation: 731
Most of the solutions for detecting the loop in a linked list say that the fast pointer need to move twice the steps of the slow pointer. Why can't we have the fast pointer be just one step ahead and if fast.next == slow
we are done.
The code would look something like this
slow = head;
fast = head.next;
while(fast.next != slow)
{
slow = slow.next;
fast = fast.next;
if(fast == null) /* No loop to begin with, break */
break;
}
return fast; /* The starting loop node*/
Edits: I meant fast.next != slow
Upvotes: 0
Views: 607
Reputation: 3470
First, because your pointers will never meet, since fast will always be one ahead of slow, and the pointers meeting is what you use to detect a cycle.
Also, if you do have loops, you will get into infinite loops. Let's say you have
1 -> 2 -> 3 -> 4
^_________|
Upvotes: 3