![]() |
Loop in single linked list
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. |
Re: Loop in single linked list
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 .
|
Re: Loop in single linked list
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. |
Re: Loop in single linked list
Code:
Node *Isloop(Node *List) |
Re: Loop in single linked list
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. |
Re: Loop in single linked list
Quote:
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? |
Re: Loop in single linked list
Great logic, now I understood. Thanks a lot.
|
| All times are GMT +5.5. The time now is 21:27. |