Reorder List

Reorder `L0 → L1 → … → Ln` into `L0 → Ln → L1 → Ln-1 → …` by splitting, reversing, and weaving in place.

Medium
Time O(n) Space O(1)
LeetCode
4 min read
linked-list fast-slow

Problem#

Given the head of a singly linked list, reorder it in place to L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → ....

Examples#

  • [1,2,3,4][1,4,2,3]
  • [1,2,3,4,5][1,5,2,4,3]

Constraints#

  • Length in [1, 5 * 10^4].

Approach#

  1. Find the middle via fast/slow.
  2. Reverse the second half in place.
  3. Weave: alternate one node from the first half and one from the reversed second half.

Solution#

Reorder List
class Solution {
public:
void reorderList(ListNode* head) {
if (!head || !head->next) return;
ListNode *slow = head, *fast = head;
while (fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; }
ListNode* second = slow->next;
slow->next = nullptr;
// Reverse second half.
ListNode* prev = nullptr;
while (second) {
ListNode* nxt = second->next;
second->next = prev;
prev = second;
second = nxt;
}
second = prev;
// Weave.
ListNode* first = head;
while (second) {
ListNode *fNext = first->next, *sNext = second->next;
first->next = second;
second->next = fNext;
first = fNext;
second = sNext;
}
}
};

Editorial#

Three classical primitives composed in sequence. Finding the middle with fast->next (instead of fast) on the condition ensures we land on the first of two middles for even-length lists, so the second half is the smaller one — exactly what we want for the weave to terminate cleanly.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.