Linked List Cycle

Write the code, see it run, pass the checks.

The problem

  • easy
  • Code

Write hasCycle(head). head is the first node of a linked list made of nodes { value, next }, or null for an empty list. Usually the last node's next is null, but here it may point back to an earlier node, or to itself, so following next would go round forever. Return true if the list has such a cycle and false if it ends. Values can repeat, so compare nodes, not values, and don't change the list. For example, for the list 3, 2, 0, -4 whose last node links back to the node holding 2, hasCycle returns true. The checks include 100,000 nodes, so searching an array of visited nodes at every step is too slow.

Your code must pass

  • Finds a cycle
  • Returns false when the list ends
  • Handles an empty list and a single node
  • Doesn't change the list
  • Is fast enough for 100,000 nodes