The following is a code to detect a loop in a linked list. This question is prepared strictly for interview purposes. This code has been modeled as per Linkedlist.java
How should I decide if a function like
hasLoop()
should be included as an instance method or should be a static method similar tosort
in Collections.java?Ideally I would inherit
Linkedlist
and add an extra functionmergeSort
to the subclass, but the interviewer would not like it, thus I should keep my solution without inheriting linkedlist for interview sake. Do you agree?
public class DetectLoopExistance<E> {
private Node<E> first;
private Node<E> last;
public void add(E element) {
final Node<E> l = last;
final Node<E> newNode = new Node<E>(element, null);
last = newNode;
if (first == null) {
first = newNode;
} else {
l.next = newNode;
}
}
private static class Node<E> {
E element;
Node<E> next;
Node(E element, Node<E> next) {
this.element = element;
this.next = next;
}
}
public boolean hasLoop() {
Node<E> fast = first;
Node<E> slow = first;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (slow == fast) {
return true;
}
}
return false;
}
}