Check if a linked list contains a loop?
This is also one of the popular coding questions about linked lists.
How we can determine if a linked list contains a loop?
A linked list that contains a loop will have the last node pointing to another node in the same list, rather than pointing to the null.
To look for a loop in a linked list, we can use the two-pointers algorithm.
We have two pointers, fast and slow are used while iterating over the linked list.
The fast pointer moves two nodes in each iteration, while the slow pointer moves to one node. If the linked list contains a loop or cycle then both fast and slow pointers will meet at some point during iteration.
If they don't meet and fast or slow will point to null, then the linked list is not cyclic and it doesn't contain any loop.
This is also called Floyd’s Cycle-Finding Algorithm.
We have two pointers, fast and slow are used while iterating over the linked list.
The fast pointer moves two nodes in each iteration, while the slow pointer moves to one node. If the linked list contains a loop or cycle then both fast and slow pointers will meet at some point during iteration.
If they don't meet and fast or slow will point to null, then the linked list is not cyclic and it doesn't contain any loop.
This is also called Floyd’s Cycle-Finding Algorithm.
Here is the Java implementation of the solution:
public boolean isCyclic() {
Node<T> fast = head;
Node<T> slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = fast.next;
if (slow == fast) {
return true;
}
}
return false;
}
The above solution is my preferred approach, but there are more ways we can check if a linked list has a loop:
Using HashSet
public boolean isCyclic() {
HashSet<Node<T>> set = new HashSet<>();
Node<T> current = head;
while (current != null) {
if (set.contains(current)) { // if true - the linked list has a loop
return true;
}
set.add(current);
current = current.next;
}
return false;
}
Using HashMap
public boolean isCyclic() {
Map<Node<T>, Integer> map = new HashMap<>();
Node<T> current = head;
while (current != null) {
if (map.containsKey(current)) { // if true - the linked list has a loop
return true;
}
map.put(current, 1); // the value is not important
current = current.next;
}
return false;
}
That is all about how to check if a linked list is cyclic or not.
No comments:
Post a Comment