LeetCode #143 Medium

Reorder List

Reorder a linked list from L0 -> L1 -> ... -> Ln into L0 -> Ln -> L1 -> Ln-1 -> ... in place.

linked-listtwo-pointersreversal
Open on LeetCode ↗
02

Intuition

💡

The pattern alternates between the front of the list and the back, but a singly linked list cannot walk backwards — so build a half that already runs backwards. Find the middle, reverse the second half, then zip the two together. The step people skip is the cut: if you reverse without first setting slow.next = None, the reversed half is still linked into the first and you have quietly built a cycle. The other trap is in the merge, where you must save both next pointers before overwriting either.

03

Approach

1

Find the middle with slow and fast pointers

Advance slow one node and fast two. When fast reaches the end, slow is at the middle. For even lengths this convention leaves the first half one node longer, which is exactly what the interleaving wants — the extra node ends up at the tail.

2

Reverse the second half

Cut the list at the middle by setting slow.next = None, then reverse the second half with the usual three-pointer loop. Now the second half is traversable from the original tail forwards, which is the access pattern the answer needs.

3

Merge alternately

Walk both halves, splicing one node from each in turn and saving the next pointers before overwriting them. Losing those references is the standard bug here. Because the first half is never shorter, the loop terminates cleanly with the second half exhausted first. All in place: O(n) time and O(1) space, versus the O(n) space of copying nodes into an array.

04

Solution & live demo

python
1class Solution:
2 def reorderList(self, head):
3 if not head or not head.next:
4 return
5 slow, fast = head, head.next
6 while fast and fast.next:
7 slow = slow.next
8 fast = fast.next.next
9 second = slow.next
10 slow.next = None
11 prev = None
12 while second:
13 nxt = second.next
14 second.next = prev
15 prev = second
16 second = nxt
17 first, second = head, prev
18 while second:
19 f, s = first.next, second.next
20 first.next = second
21 second.next = f
22 first, second = f, s
23 return
05

Edge cases

Empty or single-node list

Already in the target order — return early.

Two nodes

The pattern is unchanged, so the merge is a no-op.

Forgetting to cut at the middle

The reversed half still links back into the first, producing a cycle.

Odd length

The middle node ends up last, which the slow/fast convention handles without a special case.

06

Complexity

Time
O(n)
Space
O(1)
Middle, reverse, merge — three linear passes with no extra storage.