Reorder List Visualizer & Step-by-Step Algorithm Solution

Reorder the list to L0 → Ln → L1 → Ln-1 → L2 → Ln-2 by finding the middle, reversing the second half, and merging both halves.

Category: linked-list | Difficulty: Medium

Tags: Linked List, Two Pointers, Reversal, Merge

Reorder List

slow, fast
1
2
3
4
5
100%
state
slowNode(1)
fastNode(1)
secondnull
prevnull
firstnull
Initialization
1/14
Explanation

Initialize reorderList.

Source Code
1function reorderList(head) {
2 if (!head || !head.next) return;
3 let slow = head, fast = head;
4 while (fast.next && fast.next.next) {
5 slow = slow.next;
6 fast = fast.next.next;
7 }
8 let second = slow.next;
9 slow.next = null;
10 let prev = null;
11 while (second) {
12 const next = second.next;
13 second.next = prev;
14 prev = second;
15 second = next;
16 }
17 second = prev;
18 let first = head;
19 while (second) {
20 let firstNext = first.next;
21 let secondNext = second.next;
22 first.next = second;
23 second.next = firstNext;
24 first = firstNext;
25 second = secondNext;
26 }
27}