Reorder List
Master this topic with zero to advance depth.
Reorder List
You are given the head of a singly linked-list. The list can be represented as:
L0 → L1 → … → Ln - 1 → Ln
Reorder the list to be on the following form:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
You may not modify the values in the list's nodes. Only nodes themselves may be changed.
Visual Representation
List: 1 -> 2 -> 3 -> 4
1. Find middle: 2
2. Reverse second half: 4 -> 3
3. Merge lists: 1 -> 4 -> 2 -> 3Examples
Level I: Brute Force (Array/Stack)
Intuition
Store all nodes in an array. Use two pointers (start and end) to reorder the nodes by changing their next pointers.
Detailed Dry Run
1->2->3->4. Array: [1, 2, 3, 4].
- 1.next = 4.
- 4.next = 2.
- 2.next = 3.
- 3.next = null.
⚠️ Common Pitfalls & Tips
O(N) space makes this less efficient than in-place methods.
Visual Trace (Array/Stack)
List: 1 -> 2 -> 3 -> 4
Array: [1, 2, 3, 4]
i=0, j=3: 1.next=4, 4.next=2
i=1, j=2: 2.next=3
i=2, j=2: Break. 3.next=null
Result: 1 -> 4 -> 2 -> 3Level II: Using a Stack
Intuition
Store all nodes in a stack. Since a stack is LIFO, popping from it gives nodes from the end. Only pop N/2 nodes and interleave them with the first half of the list.
Detailed Dry Run
1->2->3->4. Stack: [1, 2, 3, 4].
- Pop 4, link after 1: 1->4->2.
- Pop 3, link after 2: 1->4->2->3. Wait, stop after N/2 swaps.
⚠️ Common Pitfalls & Tips
Be careful to set the final next pointer to null to prevent cycles.
Level III: Optimal (Middle + Reverse + Merge)
Intuition
Find the middle of the list. Reverse the second half. Merge the two halves one by one.
Detailed Dry Run
1->2->3->4.
- Mid: 2.
- Reverse 3->4 to 4->3.
- Merge (1->2) and (4->3): 1->4->2->3.
⚠️ Common Pitfalls & Tips
Ensure to cut the list at the middle (slow.next = null) to avoid cycles.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.