Linked listsAnimated
Reverse a Linked List
Flip each next pointer while walking the list.
Time
O(n)
Extra space
O(1)
Use it for
Fundamental pointer exercise.
How it works
- Use three pointers: prev (starts empty), curr (the node being processed) and next (saved so we do not lose the rest of the list).
- Save curr.next, then point curr.next backwards to prev.
- Move prev and curr one step forward.
- When curr runs off the end, prev is the new head. O(n) time, O(1) memory.
Watch it run
Loading animation…