Know this before you start: โReverse a list iterativelyโ
Reversing a linked list
Walk with three pointers (prev, current, next): save next, point current back at prev, then step forward. The old tail becomes the head.
The idea
To reverse, every node must point to the one before it. Going node by node, flip current.next to prev.
The danger: once you flip current.next, you've lost the rest of the list. So save it first in NEXT, then flip, then move prev and current one step forward.
See it step by step
Reverse 1 โ 2 โ 3
- prev = None, current = 1: save 2, 1 โ None, prev = 1, current = 2
- save 3, 2 โ 1, prev = 2, current = 3
- save None, 3 โ 2, prev = 3, current = None โ new head 3: 3 โ 2 โ 1
In code (Python)
class ListNode:
def __init__(self, val, next=None):
self.val, self.next = val, next
def reverse(head):
prev, current = None, head
while current:
nxt = current.next # save the rest
current.next = prev # flip the link
prev, current = current, nxt
return prev # the old tail
def show(head):
out = []
while head:
out.append(head.val)
head = head.next
return out
print(show(reverse(ListNode(1, ListNode(2, ListNode(3)))))) # [3, 2, 1]O(n) time, O(1) space.
When you'll use it
- Reversing a whole list or part of it, checking palindrome lists, reorder list, adding numbers stored in reverse.
Common mistakes
- Flipping before saving next.
- Returning head (now the last node) instead of prev.