Reverse Linked List
Reversing a linked list means changing the direction of the next pointers so that the last node becomes the head and the original head becomes the tail.
Iterative Approach
Traverse the list while keeping track of the previous, current, and next nodes, reversing the next pointer at each step.
def reverse_list(head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev # new head
Recursive Approach
Recursively reverse the rest of the list, then fix the pointers on the way back up the call stack.
def reverse_list_recursive(head):
if head is None or head.next is None:
return head
new_head = reverse_list_recursive(head.next)
head.next.next = head
head.next = None
return new_head
Complexity
| Approach | Time | Space |
|---|---|---|
| Iterative | O(n) | O(1) |
| Recursive | O(n) | O(n) (call stack) |
Applications
- Palindrome checking on linked lists.
- Undo functionality where operations need to be replayed in reverse.
- A common building block in problems like reversing sub-portions of a list or reversing in groups of k.
Tracing the Iterative Version Pointer by Pointer
Pointer problems become much easier once you trace them in a table. Here is the iterative algorithm running on the list 1 -> 2 -> 3 -> None:
| Step | prev | current | next_node | List state after step |
|---|---|---|---|---|
| Start | None | 1 | - | 1 -> 2 -> 3 |
| 1 | 1 | 2 | 2 | None <- 1 , 2 -> 3 |
| 2 | 2 | 3 | 3 | None <- 1 <- 2 , 3 |
| 3 | 3 | None | None | None <- 1 <- 2 <- 3 |
The loop stops when current becomes None. At that moment prev points to node 3, which is the new head. The key idea is that next_node must be saved before the link is flipped, otherwise the rest of the list is lost.
Testing It with a Small Helper
Writing tiny helpers to build and print lists lets you test edge cases quickly instead of reasoning only in your head:
class ListNode:
def __init__(self, val, next=None):
self.val = val
self.next = next
def build(values):
head = None
for v in reversed(values):
head = ListNode(v, head)
return head
def to_list(head):
out = []
while head:
out.append(head.val)
head = head.next
return out
print(to_list(reverse_list(build([1, 2, 3, 4])))) # [4, 3, 2, 1]
print(to_list(reverse_list(build([7])))) # [7]
print(to_list(reverse_list(build([])))) # []
Always test an empty list, a single node and two nodes. Most pointer bugs show up in one of those three cases.
Variation: Reverse Only Part of the List
A frequent follow-up asks you to reverse the nodes between positions left and right. Use a dummy node in front of the head, walk to the node just before left, then repeatedly move the next node to the front of the sublist:
def reverse_between(head, left, right):
dummy = ListNode(0, head)
before = dummy
for _ in range(left - 1):
before = before.next
current = before.next
for _ in range(right - left):
moved = current.next
current.next = moved.next
moved.next = before.next
before.next = moved
return dummy.next
The dummy node removes the special case where reversal starts at the head. The same idea of reversing sublists is used when reversing in groups of k.
Errors to Watch For
- Returning
headinstead ofprevat the end, which gives back the old first node, now the tail. - Skipping
head.next = Nonein the recursive version, which leaves a cycle between the first two nodes. - Using recursion on very long lists, where Python may hit its recursion limit; prefer the iterative version in production code.
- For a doubly linked list, forgetting to swap both
nextandprevon every node.
Takeaway: remember the three-pointer pattern (save next, flip link, move forward) and you can solve most reversal variations. In interviews, say the pattern out loud before coding and trace one short example; it shows clear thinking and catches mistakes early.