π Linked List: Reverse Linked List
π Problem Description
Given the head of a singly linked list, reverse the list and return its new head.
Real-World Application
Reversing a list is a fundamental operation in undo/redo functionality (if using a linked list of states) and in some network protocols where packets must be processed in reverse order.
π οΈ Constraints & Edge Cases
- The number of nodes in the list is in the range \([0, 5000]\).
- \(-5000 \le Node.val \le 5000\)
- Edge Cases to Watch:
- Empty list (
head is None). - Single node list.
- Large list (ensure iterative approach to avoid stack overflow).
- Empty list (
π§ Approach & Intuition
The Aha! Moment
Don't move the nodesβjust flip the links. By keeping track of the previous node, we can point the current node's next back to it as we move forward.
π’ Brute Force (Naive)
Creating a new list by prepending each element from the original list. This would take \(\mathcal{O}(N)\) time but also \(\mathcal{O}(N)\) space.
π Optimal Approach (Iterative In-Place)
- Initialize
prevasNoneandcurrashead. - While
curris notNone:- Save the next node:
temp = curr.next. - Reverse the link:
curr.next = prev. - Advance pointers:
prev = curr,curr = temp.
- Save the next node:
- Return
prevas the new head.
π§© Visual Tracing
graph LR
subgraph Step 1
A[1] --> B[2] --> C[3]
end
subgraph Step 2
A1[1] -.-> B1[None]
B1[2] --> C1[3]
end
π» Solution Implementation
β±οΈ Complexity Analysis
- Time Complexity: \(\mathcal{O}(N)\) β We visit each node exactly once.
- Space Complexity: \(\mathcal{O}(1)\) β We only use three pointers regardless of list size.
π€ Interview Toolkit
- Recursive Approach: Can you solve this recursively? (Hint: The stack uses \(\mathcal{O}(N)\) space).
- Sub-portion: How would you reverse only from position \(m\) to \(n\)?
π Related Problems
[Palindrome Linked List](../palindrome_linked_list/PROBLEM.md)β Uses reversal to check for symmetry.[Reorder List](../reorder_list/PROBLEM.md)β Uses reversal as a sub-step.