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
Step through node traversals and pointer redirects in real-time. Watch how list links flip sequentially:
Key Takeaway
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, making it highly optimal.