Reorder List
Picture
Turn 1→2→3→4 into 1→4→2→3. A singly linked list cannot jump to the tail repeatedly.
Predict
Which earlier patterns combine here?
Walk through the small example
Middle, reverse, then merge. Three small linked-list operations compose into the desired topology.
Mental model and complete Python solution
Do not invent one complicated pointer dance. Transform the representation: split, reverse the back half, then merge alternating fronts.
What the function promises: Mutate an acyclic singly linked list in place and return its original head.
class Node:
def __init__(self, value, next_node=None):
self.value, self.next = value, next_node
def build(values):
head = None
for value in reversed(values):
head = Node(value, head)
return head
def to_list(head):
answer = []
while head is not None:
answer.append(head.value)
head = head.next
return answer
def reverse_list(head):
previous, current = None, head
while current is not None:
following = current.next
current.next = previous
previous, current = current, following
return previous
def reorder_list(head):
if head is None or head.next is None:
return head
slow, fast = head, head
while fast.next is not None and fast.next.next is not None:
slow, fast = slow.next, fast.next.next
second, slow.next = reverse_list(slow.next), None
first = head
while second is not None:
next_first, next_second = first.next, second.next
first.next, second.next = second, next_first
first, second = next_first, next_second
return head
assert to_list(reorder_list(build([1,2,3,4]))) == [1,4,2,3]
assert to_list(reorder_list(build([1,2,3,4,5]))) == [1,5,2,4,3]
Work and storage: O(n) time and O(1) extra space.
When to recognize it: Three small linked-list operations compose into the desired topology.
Check before applying it: Failing to split before reversal or save next references can create a cycle.
Change one rule
The list may share nodes with another owner.
See what changes
In-place rewiring changes the other owner’s view; copy nodes or establish exclusive ownership first.
Connect
Linked List Cycle: Find the midpoint with two speeds.
Reverse a linked list: Turn tail access into forward traversal.
Merge two sorted linked lists: Weave two frontiers while preserving their suffixes.