Exforsys
+ Reply to Thread
Results 1 to 5 of 5

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 ...

  1. #1
    Guptha_S is offline Member Array
    Join Date
    Jan 2006
    Answers
    46

    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


  2. #2
    sammy is offline Senior Member Array
    Join Date
    Apr 2006
    Answers
    144
    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.


  3. #3
    Guptha_S is offline Member Array
    Join Date
    Jan 2006
    Answers
    46
    Thanks for your answer sammy


  4. #4
    sammy is offline Senior Member Array
    Join Date
    Apr 2006
    Answers
    144
    Gupta hope your query is solved. Let me know if you have any more doubts.I would try my best to resolve the same.


  5. #5
    miolamio is offline Junior Member Array
    Join Date
    Feb 2007
    Answers
    1
    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



Latest Article

Network Security Risk Assessment and Measurement

Read More...