← Practice · Linked list

Linked List Cycle Easy

Given the head of a singly linked list (ListNode with val, next), return true if the list contains a cycle, meaning some node can be reached again by following next pointers. Use O(1) extra space if you can.

Examples

  • 3->2->0->-4 with the tail linked back to the node at index 1 -> true
  • 1 with no cycle -> false

Define a function named hasCycle in JavaScript. ListNode (val, next) is available.

00:00▶ Visualize

JavaScript · Tab indents · Ctrl/⌘+Enter runs the tests