loading

Reverse Linked List — Step-by-Step Visualization

easyLeetCode #206Linked ListRecursion

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

Algorithm Pattern

Iterative Pointers Reassignment

Key Idea

To reverse a singly linked list, we iterate through the list and for each node, point its `next` to the previous node. We need three pointers: `curr` (current node), `prev` (previous node, initially None), and `next` (temporary to store the rest of the list before breaking the connection).

Step-by-Step Approach

  1. Initialize `prev = None` and `curr = head`.
  2. While `curr` is not None:
  3. Store `next = curr.next`.
  4. Update `curr.next = prev`.
  5. Move `prev = curr`.
  6. Move `curr = next`.
  7. Return `prev` as the new head.

Common Gotchas

  • Make sure to save `curr.next` before overwriting it, otherwise you'll lose the rest of the list.
  • The loop terminates when `curr` is None, and `prev` will be the last non-None node (the new head).

Related Problems