sagelearnai

Reverse Linked List

Difficulty: Easy · Pattern: Linked List · LeetCode #206

Given the head of a singly linked list, reverse the list and return the new head.

Examples

text
1 → 2 → 3 → 4    →   4 → 3 → 2 → 1
7 → 9            →   9 → 7
(empty)          →   (empty)

Hints

  1. Walk the list once, turning each next pointer around to point at the previous node.
  2. Save curr.next before you overwrite it.
  3. Recursive version: reverse the rest, then make head.next.next = head.

Approach

Iterate with prev = None and curr = head. For each node: save nxt = curr.next, point curr.next back to prev, then advance prev = curr and curr = nxt. When curr is None, prev is the new head. The recursive solution is elegant but uses O(n) stack space.

Complexity

Time: O(n). Space: O(1) iterative.

Python solution
def reverseList(head):
    prev, curr = None, head
    while curr:
        nxt = curr.next
        curr.next = prev
        prev, curr = curr, nxt
    return prev
JavaScript solution
function reverseList(head) {
  let prev = null, curr = head;
  while (curr) {
    const nxt = curr.next;
    curr.next = prev;
    prev = curr;
    curr = nxt;
  }
  return prev;
}