39. Reorder List
Reorder L0 → L1 → … → Ln into L0 → Ln → L1 → Ln−1 → L2 → … in place by changing links, not values.
Example 1
Input:
head = [1,2,3,4]Output:
[1,4,2,3]Example 2
Input:
head = [1,2,3,4,5]Output:
[1,5,2,4,3]Hint 1
Three classic steps: find the middle, reverse the second half, merge alternately.
Approach 1: Array of nodes
Store nodes in an array and relink with two indices.
⏱ Time O(n)💾 Space O(n)
Approach 2: Middle + reverse + weave ✅
Reuse three basic list techniques.
⏱ Time O(n)💾 Space O(1)
Reference solution for Middle + reverse + weave (time O(n), space O(1)). Each solution passes every test in all four languages.
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
# 1) find the middle
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
# 2) reverse the second half
prev, curr = None, slow.next
slow.next = None
while curr:
curr.next, prev, curr = prev, curr, curr.next
# 3) weave the two halves
a, b = head, prev
while b:
an, bn = a.next, b.next
a.next, b.next = b, an
a, b = an, bnclass Solution {
public void reorderList(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; }
ListNode prev = null, curr = slow.next; // reverse the second half
slow.next = null;
while (curr != null) { ListNode nx = curr.next; curr.next = prev; prev = curr; curr = nx; }
ListNode a = head, b = prev; // weave
while (b != null) {
ListNode an = a.next, bn = b.next;
a.next = b; b.next = an;
a = an; b = bn;
}
}
}class Solution {
public:
void reorderList(ListNode* head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }
ListNode *prev = nullptr, *curr = slow->next; // reverse the second half
slow->next = nullptr;
while (curr) { ListNode* nx = curr->next; curr->next = prev; prev = curr; curr = nx; }
ListNode *a = head, *b = prev; // weave
while (b) {
ListNode *an = a->next, *bn = b->next;
a->next = b; b->next = an;
a = an; b = bn;
}
}
};function reorderList(head) {
let slow = head, fast = head;
while (fast && fast.next) { slow = slow.next; fast = fast.next.next; }
let prev = null, curr = slow.next; // reverse the second half
slow.next = null;
while (curr) { const nx = curr.next; curr.next = prev; prev = curr; curr = nx; }
let a = head, b = prev; // weave
while (b) {
const an = a.next, bn = b.next;
a.next = b; b.next = an;
a = an; b = bn;
}
}Try solving it yourself first. Interviewers care more about how you explain the approach than about the finished code.
Watch the core idea of this problem step by step. Change the input and press Visualize.
Explained in the lesson Linked Lists.
Run your code to see results here.