Example 1
- Input
- head = [3,2,0,-4], pos = 1
- Output
- true
The four distinct nodes form A(3) → B(2) → C(0) → D(-4) → B(2). Revisiting node B proves a cycle; its value is not the criterion.
You are given the head of a linked list where the tail may loop back to an earlier node. Return true when following next pointers revisits a node and false when the list ends.
Given head, the head of a linked list, determine whether the list has a cycle. A cycle exists when some node can be reached again by continuously following the next pointer.
Return true when following next pointers revisits a node and false when the walk reaches null. Node values never decide the answer; only node identity does.
The notation pos describes the test fixture's tail connection; it is not an argument to the function. Leave all node values and next links unchanged. Assume a finite collection of nodes with stable next links during the call.
pos is minus one for no cycle, or a valid zero-based node index for the tail connection. It is fixture notation, not a function parameter.The four distinct nodes form A(3) → B(2) → C(0) → D(-4) → B(2). Revisiting node B proves a cycle; its value is not the criterion.
The second node links to the first, giving a two-node loop with no prefix before the entrance. Following next references never reaches null.
The only node has next = null. The walk ends after visiting it once, so the result is false.
The nodes have equal values but different identities, and the second points to null. Repeated data does not create a cycle.
The sole node points to itself. Both walkers return to that same object after their first movement.
A null head has no reachable node and therefore no cycle.
A linked list is a chain of node objects joined by next references. Revisiting the same object proves a cycle, even if its value is also stored elsewhere. In Example 1 label the four objects A, B, C and D: A → B → C → D → B. A set remembers these identities explicitly. Floyd's algorithm instead advances one reference by one hop and another by two; their meeting after movement proves the chain loops.
Reveal Hash Set: intuition, complexity, and code
null.fast and fast.next before each double step.When a path may loop, race a slow and a fast walker: a meeting proves a cycle and an off-the-end fall proves there is none.