The Concept#
Reversing a singly linked list is a classic pointer-manipulation exercise.
To reverse the list, we iterate through the nodes and redirect the next pointer of each node to point to its predecessor (prev) instead of its successor.
We maintain three pointers:
prev: Points to the node before the current one (initiallyNone).curr: Points to the node we are currently processing (initiallyhead).next: Temporarily stores the node aftercurrbefore we rewritecurr.next.
Code Implementation#
Below is the standard iterative implementation of Reverse Linked List:
- Time Complexity: O(N) since we visit each of the N nodes exactly once.
- Space Complexity: O(1) auxiliary space as we only modify node pointers in-place.
Interactive Lab: Reverse Linked List#
Let's take the example of this visualization: the list 10 → 20 → 30 → 40 → 50. Press play and follow the three pointers from the section above. curr walks forward one node at a time; next is parked on the node ahead so the link isn't lost the instant it's overwritten; prev trails behind, holding the part that has already been flipped. When curr falls off the end, prev is the new head and the list reads 50 → 40 → 30 → 20 → 10.
What to Remember#
Reversing pointers sequentially requires a temporary variable to hold the upcoming node (next = curr.next). Reversing in-place runs in linear time with zero extra heap allocations.