Detect a loop in cyclic/circular linked list
by · Published December 25, 2015 · Updated December 26, 2015
Logic :
- If a linked list has a cycle then no node has a null as next pointer.
- A simple loop exists when p1.next.next !== null as shown below.
Simplest possible loop
- While iterating over the linked list we need two pointers, p1 increments one node at a time and the p2 increments two points at a time. If both the pointers meet then the loop exists.
If there is no loop then p1 and p2 can not meet as p2 is in the future, we have not invented time travel yet
Circular Linked List iteration for the given solution
Watch the following video to understand the Floyds cycle-finding algorithm!
This post is a follow-up of JavaScript Linked List Example. I recommend reading those posts first, as the following code uses the method from it.
Solution :
References :
- Stackoverflow
- Floyds algorithm for cycle detection
Related Posts:
- Minimum Absolute Difference in an Array