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

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

$
0
0

If the linked list structure implements java.util.List. We can use the list size to keep track of our position in the list.

We can traverse the nodes comparing our current position to the last node's position. If our current position surpasses the last position, we've detected the list has a loop somewhere.

This solution takes a constant amount of space, but comes with a penalty of linearly increasing the amount of time to complete as list size increases.

class LinkedList implements List {    Node first;    int listSize;    @Override    int size() {        return listSize;    }    [..]    boolean hasLoop() {        int lastPosition = size();        int currentPosition = 1;        Node next = first;        while(next != null) {           if (currentPosition > lastPosition) return true;           next = next.next;           currentPosition++;        }        return false;    }}

Or as a utility:

static boolean hasLoop(int size, Node first) {    int lastPosition = size;    int currentPosition = 1;    Node next = first;    while(next != null) {       if (currentPosition > lastPosition) return true;       next = next.next;       currentPosition++;    }    return false;}

Viewing all articles
Browse latest Browse all 30

Latest Images

Trending Articles





Latest Images