Detect Cycle in Linked List
Given the head of a linked list, determine whether the list contains a cycle.
Use the Floyd's Tortoise and Hare algorithm for optimal performance.
Input: head = [3, 2, 0, -4], pos = 1
Output: true
Explanation: The tail connects to the node at position 1.
export class ListNode {
val: number;
next: ListNode | null;
constructor(val?: number, next?: ListNode | null) {
this.val = val ?? 0;
this.next = next ?? null;
}
}
export function hasCycle(head: ListNode | null): boolean {
let slow = head;
let fast = head;
while (fast !== null && fast.next !== null) {
slow = slow.next!; // moves 1 step
fast = fast.next.next; // moves 2 steps
if (slow === fast) return true; // cycle detected
}
return false;
}