Reverse a Singly Linked List

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

The problem

  • easy
  • Code

Write reverseList(head). A linked list is made of nodes { value, next }, where next is the following node, or null at the end; head is the first node, or null for an empty list. Reverse the list by relinking its nodes, without making new ones, and return the new head. For example, if list([1, 2, 3]) builds the list 1, 2, 3, then reverseList(list([1, 2, 3])) returns the list 3, 2, 1, whose head is the node that held 3. The checks include a list of 100,000 nodes, so copying into a new array at every step is too slow, and recursion that deep runs out of stack.

Your code must pass

  • Reverses a list of several nodes
  • Handles an empty list and a single node
  • Relinks the original nodes
  • Is fast enough for 100,000 nodes