16. Reverse Linked List

Difficulty:EasyPattern:Linked List Pointer ManipulationTime:O(n)Space:O(1)

Given the head of a singly linked list, reverse the list, and return the reversed list's head.

How It Works & Algorithmic Design

Solves using Three-Pointer Iterative Pointer Reversal:

  1. Pointers: Maintain prev = null, curr = head, and next = null.
  2. Traversal Loop (While curr !== null):
    • Save next node: next = curr.next.
    • Reverse pointer direction: curr.next = prev.
    • Shift pointers forward: prev = curr, curr = next.
  3. Return: prev now points to the new head of the reversed linked list.

Why This Approach Works Best

Reverses all link directions in a single pass ($O(n)$ time) without allocating extra nodes or array memory ($O(1)$ space).

Example Walkthrough
Input List: 1 -> 2 -> 3 -> 4 -> null
Singly linked list.
Pointer Reversal: null <- 1 <- 2 <- 3 <- 4 (head=4)
Pointers reversed in place.
Output Head: 4 -> 3 -> 2 -> 1 -> null
New head node is 4.

Answer: Reverse linked list iteratively

function reverseList(head) {
  let prev = null, curr = head;
  while (curr !== null) {
    const nextTemp = curr.next;
    curr.next = prev;
    prev = curr;
    curr = nextTemp;
  }
  return prev;
}
💡 Reverse node references step by step using prev, curr, and next tracking pointers.
Key Takeaways
  • Store curr.next before overwriting the node's pointer.
  • Iterative reversal works in $O(n)$ time and $O(1)$ space.
  • Return prev as the new head when curr reaches null.