Reverse Linked List
Master this topic with zero to advance depth.
Reverse Linked List
Given the head of a singly linked list, reverse the list, and return the reversed list.
Visual Representation
List: 1 -> 2 -> 3 -> null
Step 1: Current=1, Next=2. 1.next points to null.
Step 2: Current=2, Next=3. 2.next points to 1.
Step 3: Current=3, Next=null. 3.next points to 2.
Result: 3 -> 2 -> 1 -> nullExamples
Level I: Brute Force (Stack)
Intuition
Push all node values onto a stack. Since a stack is Last-In-First-Out (LIFO), popping them will give the values in reverse order. Then, create a new list with these values.
Detailed Dry Run
List: 1->2->3.
- Push 1, 2, 3 to stack.
- Pop 3: New list 3.
- Pop 2: 3->2.
- Pop 1: 3->2->1.
⚠️ Common Pitfalls & Tips
O(N) space makes this less efficient than in-place methods.
Level II: Recursive
Intuition
Base case: if head is null or next node is null, return head. Recursive step: reverse the rest of the list, then point the next node's next back to head.
Detailed Dry Run
1->2->3.
- reverseList(2->3).
- reverseList(3) returns 3.
- Back at 2: 2.next (3).next = 2. 2.next = null. List: 3->2->null.
- Back at 1: 1.next (2).next = 1. 1.next = null. List: 3->2->1->null.
⚠️ Common Pitfalls & Tips
Easy to forget to set head.next = null, causing deep cycles.
Level III: Optimal (Iterative In-place)
Intuition
Use three pointers: prev, curr, and next. Iterate through the list, changing each node's next pointer to point to the prev node.
Detailed Dry Run
1->2->3. Prev=null, Curr=1.
- Next=2. 1.next=null. Prev=1, Curr=2.
- Next=3. 2.next=1. Prev=2, Curr=3.
- Next=null. 3.next=2. Prev=3, Curr=null. Return Prev (3).
⚠️ Common Pitfalls & Tips
Make sure to return prev at the end, as curr will be null.
Visual Pointer Reversal
[1] -> [2] -> [3] -> null
p=null, c=1
Iter 1: [1].next=null, p=1, c=2
Iter 2: [2].next=1, p=2, c=3
Iter 3: [3].next=2, p=3, c=null
Return p=3: [3] -> [2] -> [1] -> nullFound an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.