Given the head of a singly linked list, check whether it has a cycle, meaning some node can be reached again by repeatedly following the next pointers.
The tail's connection point (called pos in the examples) is not provided as a parameter. Return True if a cycle exists and False otherwise.
Function Signature
from typing import Optional
class ListNode:
def __init__(self, val: int = 0, next: "Optional[ListNode]" = None):
self.val = val
self.next = next
def has_cycle(head: Optional[ListNode]) -> bool:
...
Rules
-
Each test writes the list as
head = [v0, v1, ..., vk]
plus an integer
pos
. The harness creates one node per value, links the nodes in order, and points the tail's
next
at the node with zero-based index
pos
. When
pos = -1
, the tail's
next
is
None
.
-
The function receives only the first node, or
None
for an empty list.
-
Node values can repeat. Two nodes with the same value are still different nodes.
-
An empty list has no cycle. A single node whose
next
points to itself is a cycle.
Constraints
-
0 <= number of nodes in the list <= 10^4
-
-10^4 <= Node.val <= 10^4
Examples
Input: head = [5, 7, 9, 2], pos = 2
Output: True
The tail (value 2) links back to the node at index 2 (value 9), so the walk 9 -> 2 -> 9 repeats forever.
Input: head = [4, 8], pos = 0
Output: True
The tail links back to the head, so both nodes are on the cycle.
Input: head = [3, 1, 4], pos = -1
Output: False
The last node's next is None, so following the pointers reaches the end of the list.