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:
prevto track the previous node.curras the current node.nextto 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.