Reorder List
Difficulty: Medium · Pattern: Linked List · LeetCode #143
Rearrange the list L0 → L1 → … → Ln−1 → Ln in place into L0 → Ln → L1 → Ln−1 → L2 → …. Modify the nodes' links; don't just change values. Return nothing (the tests read the list from the original head).
Examples
text
1 → 2 → 3 → 4 → 1 → 4 → 2 → 3
1 → 2 → 3 → 4 → 5 → 1 → 5 → 2 → 4 → 3Hints
- The result alternates between the front half and the reversed back half.
- Combine three classic routines: find the middle, reverse a list, merge two lists alternately.
Approach
- Find the middle with fast/slow pointers, and cut the list after
slow. - Reverse the second half.
- Interleave: take one node from the first half, then one from the reversed second half, and repeat.
All in place with O(1) extra space.
Complexity
Time: O(n). Space: O(1).
Python solution
def reorderList(head):
if not head or not head.next:
return
slow, fast = head, head.next
while fast and fast.next:
slow, fast = slow.next, fast.next.next
second, slow.next = slow.next, None # cut
prev = None # reverse second half
while second:
second.next, prev, second = prev, second, second.next
first, second = head, prev # interleave
while second:
n1, n2 = first.next, second.next
first.next, second.next = second, n1
first, second = n1, n2JavaScript solution
function reorderList(head) {
if (!head || !head.next) return;
let slow = head, fast = head.next;
while (fast && fast.next) { slow = slow.next; fast = fast.next.next; }
let second = slow.next; slow.next = null;
let prev = null;
while (second) { const nxt = second.next; second.next = prev; prev = second; second = nxt; }
let first = head; second = prev;
while (second) {
const n1 = first.next, n2 = second.next;
first.next = second; second.next = n1;
first = n1; second = n2;
}
}