Weave a linked list first, last, second, second to last. Find the middle with slow and fast pointers, reverse the back half, then merge.
▼The problem
LeetCode 143 (Medium). Given the head of a singly linked list L0 → L1 → … → Ln, reorder it in place to L0 → Ln → L1 → Ln−1 → L2 → … Only the links may change, not the values in the nodes.
Examples (LeetCode's): [1,2,3,4] → [1,4,2,3] and [1,2,3,4,5] → [1,5,2,4,3] (the walkthrough).
The solution
def reorderList(head):
slow = fast = head
while fast.next and fast.next.next:
slow, fast = slow.next, fast.next.next
prev, cur = None, slow.next
slow.next = None # cut
while cur:
nxt = cur.next
cur.next = prev # flip
prev, cur = cur, nxt
first, second = head, prev
while second:
n1, n2 = first.next, second.next
first.next = second
second.next = n1
first, second = n1, n2Transcript
Reorder List. Picture a linked list as a parade of circus elephants, each holding the next one's tail with its trunk. Reorder the parade in place: first, last, second, second to last, and so on, until the two ends meet in the middle.
So one, two, three, four becomes one, four, two, three. One through five becomes one, five, two, four, three. And only the links may change: who holds whose tail. The numbers stay on their elephants.
The easy way copies the elephants into an array and reads it from both ends. That works, but the array costs order n extra space. Without it, you'd walk to the tail for every link, and those walks add up to order n squared time.
Look at the answer instead. The front half keeps its order, and the back half comes in backwards, slotted in between. So there are three steps: find the middle, reverse the back half, then merge the two halves, one from each in turn. For the middle, send two pointers from the head. Slow takes one step while fast takes two, so when fast reaches the end, slow is halfway.
Let's run one through five. Slow goes to two as fast goes to three. Slow goes to three as fast reaches five, the end. So three is the middle. Cut the rope after three. Reverse the back half: four lets go, and five turns around to hold four. Now merge: one takes five, five takes two, two takes four, and four takes three. One, five, two, four, three.
In code, slow and fast walk while fast can take two more steps. Cut after slow, then flip the back half's links one by one. Then, while the back half has nodes, point first at second, point second at first's old next, and step both forward.
Each step is a single pass, so the time is order n. Only a few pointers ever move, so the extra space is order one.
Middle, reverse, merge. That's Reorder List.