dsa · easy
Linked List Cycle
You are given the head of a singly linked list. Each node has val and next. Return whether following next ever comes back to a node you already visited.
Arguments
head— aListNode(val,next);Noneif the list is empty
Only head. Walk .next. Empty list → false.
Example
3 → 2 → 0 → -4 with the tail linked back to 2:
`` 3 → 2 → 0 → -4 ↑ | └─────────┘ ``
Samples print **node values**, then how the judge wired the tail (an index, or -1 for no cycle). That second number is **not** a parameter. If it were, return pos != -1 would solve the problem.
Constraints
0 <= number of nodes <= 4*10^4 Hidden tests include near-max size for this bound; a slower-than-intended solution TLEs.
Examples
Example 1
Input: [3,2,0,-4] 1 Expected: true
Example 2
Input: [1,2] -1 Expected: false