Wednesday 28 June 2017

detect a loop in a linked list

Visited flag
 Have a visited flag in each node of the linked list. Flag it as visited when you reach the node. When you reach a node and the flag is already flagged as visited, then you know there is a loop in the linked list.

Using 2 Pointers
  Increment one pointer by 1 node and the other by 2 nodes. If there's a loop, the 2nd pointer will meet the 1st pointer somewhere. If it does, then you know there's one.

p=head;
q=head->next;
 while(p!=NULL && q!=NULL) {
  if(p==q) {
     //Loop detected!
      exit(0);
    }
   p=p->next;
   q=(q->next)?(q->next->next):q->next;
  }

 // No loop. 

No comments:

Post a Comment