Detect a cycle with fast and slow pointers
JavaScriptfunction hasCycle(head) {
let slow = head;
let fast = head;
while (fast !== null && fast.next !== null) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}Explanation
If the structure is a normal list, fast eventually hits null. If a loop exists, the fast pointer keeps circling and eventually catches the slow pointer because it moves faster inside the same cycle.
Output
Returns true when a cycle exists, otherwise false
Real-life Example
Imagine two runners on a circular track, one running twice as fast. If both keep going, the faster runner must eventually catch the slower one.