Linked List Cycle
You get the head of a linked list. The last node may point back to some earlier node instead of to none, and then walking the list never ends. Return true if the list loops like that and false if it ends. Our example: 4 → 9 → 1 → 7 → 3 → 8 → 6, and 6 points back to 1 — the answer is true.
- input
head: the head of a linked list, maybe empty. Its last node may link back to one of its nodes: the tests say which aspos, its index (−1: none).posis not passed to the function.- returns
trueif the list has a cycle,falseotherwise.- constraints
- 0 ≤ nodes ≤ 1000
- −10⁵ ≤ Node.val ≤ 10⁵
- pos is −1 or an index of the list
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
function hasCycle(head) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more fast and slow pointers problems
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.