Linked List Cycle
easy · Floyd's tortoise and hare
You are given the head of a linked list. Determine whether the list contains a cycle — i.e. whether some node's next pointer points back to an earlier node in the list. Return True if there is a cycle, False otherwise. Do not modify the list. The tests build cycles by connecting the tail to the node at a given index (pos); pos = -1 means no cycle.
Constraints
0 ≤ nodes ≤ 10^4; -10^5 ≤ val ≤ 10^5.
Examples
[3,2,0,-4] with tail connected to index 1 → True
[1,2] with tail connected to index 0 → True
[1] with no cycle → False
Starter code
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def has_cycle(head: ListNode | None) -> bool:
pass
Loading editor…
Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.
Return to the Python interpreter