1

Given below an example of Singly linked list which contains loop

node_1 --> node_2 --> node_3 --> node_4 --> node_5 --> node_3

i want to detect whether loop exists or not for any given linked list by taking performance factor into consideration .

1

2 Answers 2

1

Initialize a hash. Iterate over the list. For each node, if it's already in the hash, return LOOP. Otherwise, add it to the hash. When end of list is reached, return NO_LOOP.

Note: you don't have to put the entire node in the hash. An identifier is enough, or anything else that identifies the node uniquely.

Sign up to request clarification or add additional context in comments.

4 Comments

I think that's less efficient than Floyd's cycle finding algorithm since it's O(n) storage
It uses more memory, but its actual running time should be shorter (even though they're both O(n)).
I guess it depends how big the subset that forms the loop is, if it exists. I suspect it's one of those things that in the real world you'd pick one for certain sized lists and another for the others after measuring actual implementations.
@EranZimmerman: This will use more memory if list size is more than 10000 (suppose).storing data to other data structure should be avoided and we should avoid modification of data in Node too.
0
function boolean hasLoop(Node startNode){
      Node slowNode = Node fastNode = startNode;
      while(true){
          if(slowNode)
             return false;
          else if(((slowNode==fastNode)&&fastNode!=startNode)||fastNode->next==slowNode)
              return true;
          else{
              slowNode=slowNode->next;
              fastNode=fastNode->next->next;
          }
      }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.