Visualize

Pattern visualizer

Reorder List

The target order interleaves the first half read forward with the second half read backward, but a singly linked list has no way to walk backward, so the second half must actually be reversed before anything can be spliced. Fast and slow pointers find the midpoint in one pass: fast covers two nodes for every one slow covers, so fast hits the end exactly when slow is at the middle. Cutting the list there gives two independent chains; reversing the second one in place turns it into last-to-first order. From there, splicing alternates a node from the first chain with a node from the reversed second chain, always saving both next pointers before either is overwritten. The first half is never shorter than the second, so the loop can end the moment the second chain runs out. Animated on: list = [1, 2, 3, 4, 5]. Reorder in place so it reads first[0], last[0], first[1], last[1], ... — L0 -> Ln -> L1 -> Ln-1 -> ... Answer: [1, 5, 2, 4, 3]..

Find the middle, reverse the back half, splice the two together

time O(n)space O(1)step 1 / 11
1
[0]
2
[1]
3
[2]
4
[3]
5
[4]
line 3

list = [1, 2, 3, 4, 5]. The target order zips the first half forward with the second half backward, which a singly linked list can't read off directly — the split point has to be found first. slow and fast both start at the head; fast moves two nodes for every one slow moves, so when fast runs out of room slow is sitting exactly at the midpoint.

Pseudocode
1FUNCTION reorderList(head)
2 slow <- head, fast <- head
3 WHILE fast.next != NULL AND fast.next.next != NULL
4 slow <- slow.next
5 fast <- fast.next.next
6 second <- REVERSE(slow.next)
7 slow.next <- NULL
8 first <- head
9 WHILE second != NULL
10 tmp1 <- first.next
11 tmp2 <- second.next
12 first.next <- second, second.next <- tmp1
13 first <- tmp1, second <- tmp2
14 RETURN head

← / → step · space play · Home restart

Where to practice Linked List