Reorder List
Reorder a linked list to alternate front and back nodes in place
DSA, Medium, Linked List
Which structure or algorithm, and what does it cost.
A linked list holds the values v1, v2, ..., vn in order. Rearrange its nodes so the list reads v1, vn, v2, vn-1, v3, ...: one from the front, one from the back, and so on until all nodes are used. Relink the existing nodes. A node has val and next. Your code gets the first node. It may relink in place and return nothing, or return the first node of the result; either is fine. The examples show the list as its values, front to back, to keep them short.
Examples
Constraints
- 1 <= length of the list <= 100,000.
- Each value is a whole number between -1,000,000 and 1,000,000.
- Aim to use O(1) extra memory beyond the nodes themselves.
Your answer must contain
- The simple method and its cost; the better method; code; time and memory cost; a hand trace of example 1 showing the halves after the cut and after the reverse.
Target Aim for O(n) time and O(1) extra memory.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
A singly linked list cannot step backward. Think about what you need so that the last node can be reached from the front.
Hint 2 the approach
Split the list into a front half and a back half. Then take one node from each half in turn.
Hint 3 the key step
Find the middle with two pointers that move at different speeds. Reverse the second half. Then link the two halves alternately.
Walkthrough
Full walkthrough brute force to best
Brute force
For each position from the front, walk to the last node, cut it off, and link it after the current front node. Each walk is O(n) and there are about n / 2 of them, so the time is O(n^2). That is far too slow for 100,000 nodes, and the memory is O(1).
Better method
Store every node in an array. Then link them with two indexes, one from the front and one from the back, taking one from each in turn. The time is O(n), but the array uses O(n) memory.
Best method
Do three small jobs. First, find the middle with a slow and a fast pointer; slow ends on the last node of the first half. Second, cut the list there and reverse the second half, so its nodes now run from the old tail back to the middle. Third, weave: take one node from the first half, then one from the reversed half, and repeat. The reversed half starts with the old last node, and the weave links it right after the first node, which is the order the question wants. The first half is never shorter than the second, so the weave stops when the second half is used up, and any extra middle node stays at the end. Every step touches each node a constant number of times.
Hand trace
Run on [1, 2, 3, 4, 5]. The pointers stop with slow on 3. Cut after 3: the first half is [1, 2, 3] and the second half is [4, 5]. Reverse the second half: [5, 4]. Weave: link 1 to 5, then 5 to 2, so the list starts 1, 5, 2. Link 2 to 4, then 4 to 3. The second half is used up. Node 3 already ends the list. The result is [1, 5, 2, 4, 3].
Code
class Node:
def __init__(self, val, nxt=None):
self.val = val
self.next = nxt
def reorder_list(head): # head is the first node; the list changes in place
slow = fast = head # slow ends on the last node of the first half
while fast.next and fast.next.next:
slow, fast = slow.next, fast.next.next
prev, cur = None, slow.next
slow.next = None # cut the list into two halves
while cur: # reverse the second half
nxt = cur.next
cur.next = prev
prev, cur = cur, nxt
first, second = head, prev
while second: # weave the two halves together
a, b = first.next, second.next
first.next = second
second.next = a
first, second = a, b
return head
# Test helper, not part of the answer: builds a list of nodes from values and reads it back.
def build(values):
head = None
for v in reversed(values):
head = Node(v, head)
return head
def to_values(head):
out = []
while head:
out.append(head.val)
head = head.next
return outTime and memory
O(n) time: finding the middle, reversing and weaving each take one pass. O(1) extra memory: a few pointers. The nodes are relinked in place.
Common mistakes
- Not cutting the list after the middle. The first half then still points into the second half and the weave makes a loop.
- Cutting the first half in the wrong place. Either middle rule works if you cut right after slow; check the even case by hand.
- Reversing the whole list instead of only the second half.
- Losing the next node before relinking. Save it first, then change the link.