Algorithm-Day23-Reverse-Linked-List-lc-206
🧩 Problem Description
Given the head of a singly linked list, reverse the list and return the new head.
Example:
1 | Input: 1 → 2 → 3 → 4 → 5 |
💡 Brute Force (Not In-Place)
- Store values in an array or stack, then rebuild the list.
- ❌ Not optimal — uses extra space.
💡 Optimal Approach: Iterative In-Place Reversal
✨ Key Idea
- Use 3 pointers:
prev
to track the previous node.curr
as the current node.next
to temporarily holdcurr.next
.
At each step:
- Reverse the link:
curr.next = prev
- Move forward
🔢 Java Code (Iterative)
1 | class Solution { |
🔁 Java Code (Recursive)
1 | class Solution { |
⏱ Time and Space Complexity
- Time Complexity: O(n)
- Space Complexity:
- Iterative: O(1)
- Recursive: O(n) (due to recursion stack)
✍️ Summary
- This is a fundamental linked list pattern — useful in many real problems (e.g., palindrome check, list reordering).
- Understand both iterative and recursive versions.
Learn it well — this reversal logic appears often in interviews and linked list puzzles.