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 .

asked Oct 7, 2011 at 10:33
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.

answered Oct 7, 2011 at 10:42
4
  • I think that's less efficient than Floyd's cycle finding algorithm since it's O(n) storage Commented Oct 7, 2011 at 10:44
  • It uses more memory, but its actual running time should be shorter (even though they're both O(n)). Commented Oct 7, 2011 at 10:49
  • 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. Commented Oct 7, 2011 at 10:58
  • @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. Commented Oct 10, 2011 at 9:43
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;
 }
 }
 }
answered Oct 13, 2011 at 12:41

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.