Linked List Cycle

Easy#141cycle

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 as pos, its index (−1: none). pos is not passed to the function.
returns
true if the list has a cycle, false otherwise.
constraints
  • 0 ≤ nodes ≤ 1000
  • −10⁵ ≤ Node.val ≤ 10⁵
  • pos is −1 or an index of the list
our 14 tests keep to them
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

14 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more fast and slow pointers problems

Pattern “Fast and slow pointers” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.