Given the head of a linked list, determine if the linked list has a cycle in it. A cycle exists if there is some node in the list that can be reached again by continuously following the next pointer. Return true if there is a cycle, false otherwise.
head = [3,2,0,-4], pos = 1truehead = [1,2], pos = 0truehead = [1], pos = -1falseslow = head, fast = headfast != null && fast.next != nullslow = slow.next (+1 step)fast = fast.next.next (+2 steps)slow == fast → cycle detected, return truereturn falseIf a cycle exists, fast enters the loop first. From that point, every iteration reduces the gap between slow and fast by 1 (fast gains 2, slow gains 1 → net gain 1 per iteration). The gap starts at most L (loop length), so they meet within L additional iterations — O(n) total.
If no cycle, fast will reach a null node (or a node whose .next is null) within O(n/2) steps.