The normal scenario to find the loop in the linked list is to move a pointer once and move other pointer two times.If they meet,there is a loop in the linked list.
But what will happen if i move the second pointer three times or four times.Will it reduce the complexity?Why we need to move second pointer two times only.
boolean hasLoop(Node first) {
Node slow, fast;
slow = fast = first;
while(true) {
slow = slow.next;
if(fast.next != null)
fast = fast.next.next;
else
return false;
if(slow == null || fast == null)
return false;
if(slow == fast)
return true;
}
}
Instead of fast.next.next,why cant i have fast.next.next.next or fast.next.next.next.next.next?