Loop in single linked list

Go4Expert Member
6May2008,12:37   #1
mr.anandc's Avatar
How to find a loop in a single linked list? The loop can be to any node in the list i.e., last node of the list can loop back to any existing node in the list.

Thanks.
TechCake
6May2008,13:17   #2
asadullah.ansari's Avatar
Take two pointer one pointing to head and increment it by one by one. and second pointer also point to head and increment it by two and check these two pointer for eqaulity. If equal then loop is there .
Go4Expert Member
6May2008,13:45   #3
mr.anandc's Avatar
Thanks for the reply.

I haven't got the concept. Suppose if I have a linked list of 10 nodes and last node is pointing back to second node, how this procedure will find a loop.

Thanks.
TechCake
6May2008,14:12   #4
asadullah.ansari's Avatar
Code:
Node *Isloop(Node *List)
{
  Node *ptr1=List, *ptr2=List,*ptr=NULL;
  while( (ptr1!=NULL) && (ptr2!=NULL))
  {
    if (ptr && (ptr1 == ptr2))
    {
      return ptr;
    }
    ptr = ptr1;
    ptr1=ptr1->next;
    ptr2=ptr2->next;
    if (ptr2)
    {
      ptr2=ptr2->next;
    }
  }
}
Go4Expert Member
6May2008,16:37   #5
mr.anandc's Avatar
Thanks for the code.

Can please explain behavior of this for the above scenario I mentioned like, 10 nodes in the list and last node pointing back to 2nd node. In this case how the code will find the loop.
TechCake
6May2008,17:55   #6
asadullah.ansari's Avatar
Quote:
Originally Posted by mr.anandc
Thanks for the code.

Can please explain behavior of this for the above scenario I mentioned like, 10 nodes in the list and last node pointing back to 2nd node. In this case how the code will find the loop.
ptr1 1 2 3 4 5 6 7 8 9 10
ptr2 1 3 5 7 9 2 4 6 8 10

So loop is there bcoz ptr1==ptr2.
Here 1 2 3 etc represent node1 node2 node3 etc

Now I think you can understand. If Any doubt ask me?
Go4Expert Member
7May2008,09:38   #7
mr.anandc's Avatar
Great logic, now I understood. Thanks a lot.