Return true if the linked list has a cycle. In the input, pos is the index the tail links back to (-1 means no cycle).
Move slow one step and fast two steps at a time. In a cycle, fast gains one step per move and must land on slow; otherwise fast falls off the end.
1function hasCycle(head: ListNode | null): boolean {2let slow = head, fast = head;3while (fast && fast.next) {4slow = slow!.next;5fast = fast.next.next;6if (slow === fast) return true;7}8return false;9}
Both start at head.
Space: play/pause · ←/→: step