Reverse the direction of all pointers in a singly linked list in-place. Β β± Time
O(n)Β πΎ SpaceO(1)
Use three pointers: prev, curr, and next. For each node, save the next pointer, reverse the current pointer to point backwards, then advance all three pointers forward. When curr is None, prev is the new head.
Algorithm:
prev, curr = None, head
while curr:
next = curr.next β save before overwriting
curr.next = prev β reverse the pointer
prev = curr β advance prev
curr = next β advance curr
return prev β new head
Original: A β B β C β D β None
Step 1 (curr=A): save B, A.next=None, prev=A, curr=B
None β A B β C β D β None
Step 2 (curr=B): save C, B.next=A, prev=B, curr=C
None β A β B C β D β None
Step 3 (curr=C): save D, C.next=B, prev=C, curr=D
None β A β B β C D β None
Step 4 (curr=D): save None, D.next=C, prev=D, curr=None
None β A β B β C β D
Return prev=D β new head! D β C β B β A β None β
Linked list reversal is one of the most iconic interview problems. It appears in nearly every data structures curriculum and is often the first "pointer manipulation" problem taught. The iterative O(1) space solution is a classic test of pointer fluency.
- Iterative (shown above): O(1) space β preferred in interviews
- Recursive: O(n) stack space β elegant but risk of stack overflow
- Always save
curr.nextBEFORE overwritingcurr.next - To reverse a portion (LeetCode 92): find the sublist boundaries, reverse, then reconnect
- Follow-ups: reverse in groups of K (LeetCode 25), check if list is palindrome (reverse second half)
- Undo/redo operations (reverse action history)
- Browser back navigation
- Text editor cursor movement
- Transaction rollback sequences
- Detect Cycle Linked List β Floyd's algorithm
- Rotate Linked List β rotate by K positions
- Merge K Lists β linked list merging