Detect a loop in cyclic/circular linked list
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.
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
andp2
can not meet asp2
is in the future, we have not invented time travel yet :)
Watch the following video to understand the Floyd's 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.