Reversing a linked list is THE fundamental linked list operation. It appears in interviews constantly, and you'll use this technique in dozens of other problems. 🔄
💡 Think of it like this: Imagine a chain of paper clips linked together: A → B → C → D. To reverse it, you need to flip each connection one by one, so it becomes D → C → B → A.
The Algorithm — Three Pointers:
You need three pointers moving through the list like a caterpillar:
prev — the node behind us (starts as None)current — the node we're at right now (starts at head)next_node — saved reference to the next node (so we don't lose it!)💭 Now it's your turn! Using the approach above, implement your solution in the editor. You've got this! 💪
Step-by-step trace (1→2→3):
Complexity: Time O(n) — visit every node once. Space O(1) — only 3 pointer variables.
def reverse(head):
prev = None
current = head
while current:
next_node = current.next # 1. Save next (don't lose it!)
current.next = prev # 2. Reverse the arrow ←
prev = current # 3. Move prev forward →
current = next_node # 4. Move current forward →
return prev # prev is now the new head!
Run your code
5
4
3
...