Interview Question
This will check for circular linked list, what if the list has a cycle like : a->b->c->d->e->c Note e points back to c.
We need to have 2 pointers move first by one and second pointer by 2 and see if they are equal any time.
here the question itself contains 2 questions. from the above answers you can find if the linkedlist is circular or not. but consider the case where the linkedlist is not circular but it has a loop. this is the tricky thing. now we have to write a code for it. the logic is if in a circular path 2 cars run one at a speed of 2MpH and other at 4MpH then sometime they will meet at the starting point. so if the speed going car is started xM before the slow going car then the meeting point will be xM before the starting point. by taking this as the reference the code of the above question is:
public int detectloop(){
node fast = head;
node slow = head;
while(fast != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
break;
}
}
slow = head;
while(fast != slow){
slow = slow.next;
fast = fast.next;
}
return fast.key;
}
you can verify the correctness of the code. the worst case complexity is O(n^2);
p = head,
- ouyang498 May 11, 2011p->next and compare to head,
if ==, cicular
if null some time, terminate?