Tuesday, February 21, 2012

Detect loop in a singly linked list.

Write code to detect a loop in a linked list.


Approach:
Keep 2 pointers at the head, say front and back.
Now move the front twice the speed as the back, if before back completing the one loop, the front pointer reaches back or overtakes it then there is loop in the singly link list.

1 comment:

  1. You can find out the cycle or loop in a single linked list by using two pointer approach.
    Below link can be useful to find out the algorithm to find cycle or loop in linked list

    find out the cycle or loop in a single linked list in java

    ReplyDelete