How linked list reversal works
Three pointers walk the list together. prev starts as null and curr at the head. On each iteration: save the next node so the rest of the list is not lost, point curr.next back at prev, then advance prev to curr and curr to the saved node. When curr becomes null, prev is the new head.
The Python example turns 1 → 2 → 3 → 4 into 4 → 3 → 2 → 1.
What to watch for when it runs
- Each iteration flips exactly one arrow.
- Between the flip and the advance the list is briefly in two pieces, and the saved next pointer is the only thing holding on to the second one.
- Delete the line that saves the next node and run it again to see the rest of the list become unreachable.
Time and space complexity
- Time
- O(n)
- Space
- O(1)
Every node is visited once and only three pointers are kept. The recursive version is just as fast but uses O(n) stack.