algorithmfree

Reverse a linked list

Flip every next pointer in place, using three pointers: prev, curr and nxt.

time
O(n)
space
O(1)

// step through it

step 1 / 14
1function reverse(head) {2  let prev = null, curr = head;3  while (curr !== null) {4    const nxt = curr.next;5    curr.next = prev;6    prev = curr;7    curr = nxt;8  }9  return prev;10}
  1. nullprev
  2. 1curr
  3. 2
  4. 3
  5. 4
  6. null

prev starts at null and curr at the head, 1.

How it works

Walk the list once. For each node, first remember its next node, then point it back at the previous node, then move both pointers forward. When curr falls off the end, prev is the new head. O(n) time and O(1) extra space.