
- Forum
- Programming Talk
- C and C++
- Loop in a single linked list
Loop in a single linked list
This is a discussion on Loop in a single linked list within the C and C++ forums, part of the Programming Talk category; Hi, How to detect a loop in a singly linked list without using any additional pointers (and without deleting any ...
-
Loop in a single linked list
Hi,
How to detect a loop in a singly linked list without using any additional pointers (and without deleting any nodes)?
Thanks
Guptha
-
There are various ways for detect a loop in a singly linked list. But as per your requirement one of the ways of doing this is traverse the list and mark each node as having been seen. If you come to a node that has already been marked, then you know that the list has a loop.There are of course some drawbacks in this method but it would achieve the purpose of detecting the loop.
-
Thanks for your answer sammy
-
Gupta hope your query is solved. Let me know if you have any more doubts.I would try my best to resolve the same.
-
You should use two pointers and iterate nodes.
Say, first pointer will iterate list from the beginning 1 node per step;
Second will iterate list 2 nodes per step.
If pointers meet each other, that means you're inside the loop.
This won't require any additional data for instances (e.g. flags, indicating previous visits).
-
Sponsored Ads

Reply With Quote





