Saturday, January 14, 2012

Finding Loop in a single linked list.


Method-1
If the linked list is read only, take two pointer approach( p1, p2). Both pointing to beginning of linked list. Now increment p1 by 1 and p2 by 2 and compare both. if they are equal there is a cycle. Repeat this untill p2 points to null.

Method-2
If you have the condition not to modify the node but you can change the links, then reverse the linked list. If you reach the head node then there is a cycle.

No comments:

Post a Comment