Overview
Given a singly linked list L0 → L1 → … → Ln-1 → Ln, reorder it to: L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …
You must modify the list in-place — do not create new nodes, only rearrange the pointers.
Constraints
- The list has 1 to 50,000 nodes.
- Node values are integers.
- Modify the list in place and return the head.
Examples
// 1 -> 2 -> 3 -> 4 reorderList(head); // => 1 -> 4 -> 2 -> 3
// 1 -> 2 -> 3 -> 4 -> 5 reorderList(head); // => 1 -> 5 -> 2 -> 4 -> 3
Solution
Reveal solution
function reorderList(head) {
if (!head || !head.next) return head;
// 1. Find middle
let slow = head, fast = head;
while (fast.next && fast.next.next) {
slow = slow.next;
fast = fast.next.next;
}
// 2. Reverse second half
let prev = null, curr = slow.next;
slow.next = null;
while (curr) {
const next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
// 3. Merge alternating
let first = head, second = prev;
while (second) {
const tmp1 = first.next, tmp2 = second.next;
first.next = second;
second.next = tmp1;
first = tmp1;
second = tmp2;
}
return head;
}Three steps: find middle with slow/fast, reverse the second half, merge by alternating nodes.
Resources
rearrange-linked-list.js
Rearrange Linked List
hardcodingAlgorithmsLinked Lists
Overview
Given a singly linked list L0 → L1 → … → Ln-1 → Ln, reorder it to: L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …
You must modify the list in-place — do not create new nodes, only rearrange the pointers.
Constraints
- The list has 1 to 50,000 nodes.
- Node values are integers.
- Modify the list in place and return the head.
Examples
// 1 -> 2 -> 3 -> 4 reorderList(head); // => 1 -> 4 -> 2 -> 3
// 1 -> 2 -> 3 -> 4 -> 5 reorderList(head); // => 1 -> 5 -> 2 -> 4 -> 3
Solution
Reveal solution
function reorderList(head) {
if (!head || !head.next) return head;
// 1. Find middle
let slow = head, fast = head;
while (fast.next && fast.next.next) {
slow = slow.next;
fast = fast.next.next;
}
// 2. Reverse second half
let prev = null, curr = slow.next;
slow.next = null;
while (curr) {
const next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
// 3. Merge alternating
let first = head, second = prev;
while (second) {
const tmp1 = first.next, tmp2 = second.next;
first.next = second;
second.next = tmp1;
first = tmp1;
second = tmp2;
}
return head;
}Three steps: find middle with slow/fast, reverse the second half, merge by alternating nodes.
Resources
NameTopicDifficulty
103 of 103 problems