Detect Loop in a Linked List
EasyP1Coding
Given the head of a singly linked list, return true if the list contains a cycle (some node can be reached again by following next), and false otherwise.
A list node has val and next. The ListNode class is already defined for you. Aim for O(1) extra space.
In the examples and tests, a list with a cycle is written as {"list": [...], "pos": k}: the values in order, and the tail's next points back to the node at index k. A plain array is a list without a cycle.
Example 1
- Input
- head = [3,2,0,-4], pos = 1
- Output
- true
- Why
- The tail connects back to the node with value 2.
Example 2
- Input
- head = [1,2], pos = 0
- Output
- true
Example 3
- Input
- head = [1]
- Output
- false
Constraints
- 0 <= number of nodes <= 10^4
- -10^5 <= Node.val <= 10^5
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 8. ⌘Enter runs, ⌘⇧Enter submits.