Quantcast
Channel: How to detect a loop in a linked list? - Stack Overflow
Viewing all articles
Browse latest Browse all 30

Answer by Ankit kaushik for How to detect a loop in a linked list?

$
0
0

I read through some answers and people have missed one obvious solution to the above problem.

If given we can change the structure of the class Node then we can add a boolean flag to know if it has been visited or not. This way we only traverse list once.

Class Node{ Data data; Node next; boolean isVisited;}public boolean hasLoop(Node head){     if(head == null) return false;     Node current = head;     while(current != null){      if(current.isVisited) return true;      current.isVisited = true;      current = current.next;     }    return false;}

Viewing all articles
Browse latest Browse all 30

Latest Images

Trending Articles





Latest Images