Problem
Given the head of a linked list, return True if the list contains a cycle, meaning some node's next points back to an earlier node so following next never ends. Return False otherwise.
Example 1
- Input
- 3
- Output
- 2 -> 0 -> -4
Example 2
^ |
Example 3
- Input
- +----------+
- Output
- True
- Why
- tail links back to the 2
Example 4
- Input
- 1
- Output
- 2 -> 3 -> (end) → False
Example 5
- Input
- (empty)
- Output
- False
Can you solve it with O(1) extra memory?
The tests build each list for you (with build_list / buildList) and link the tail to make a cycle where needed.
Constraints
0 <= number of nodes <= 10^4-10^5 <= Node.val <= 10^5