Reference Surgery: Reverse, Merge, Split
Rewire singly linked lists in place—reversal, sorted merge and middle splitting—by sketching before-and-after reference states so no tail is dropped or looped.
Contentsand lesson path
On this page
- The problem
- Step 1: in-place reversal—save nxt before turning the arrow
- Step 2: sorted merge with a stack-local sentinel and stability
- Step 3: splitting at the first middle without infinite recursion
- Check your understanding
- Apply it
- Review prompt
Lessons of Linked Lists
- Nodes, References and Sentinels Concept · 20 min
- Lab: A Doubly Linked List with a Sentinel Lab · 30 min
- Reference Surgery: Reverse, Merge, Split Worked example · 25 min
- Two Speeds Through One List Worked example · 20 min
- Lists, Arrays or Deques? Concept · 15 min
- Check: Linked List Exercises Knowledge check · 8 questions
What you will learn
- Reverse, merge and split linked lists by rewiring references, sketching before and after states so no node is lost.
Prerequisites: Complexity Analysis
01. The problem
In Lab: A Doubly Linked List with a Sentinel, every node carried both prev and next pointers. On singly linked lists, however, each node holds only a forward .next link—meaning that overwriting node.next destroys your only handle to the rest of the chain unless you saved it first.
In this worked example we walk through three core singly linked operations under a strict O(1) auxiliary space constraint (relinking existing nodes in place without allocating a new list of nodes): reverse, merge two sorted lists, and split at the middle for merge sort. Sketching before-and-after references on small 2-node to 4-node examples makes the required statement order unmistakable.
Simplification note: mutating .next links in place assumes the caller surrenders the original head variables (h, a, b); if another part of your program still reads the original unreversed order, you must copy nodes into fresh objects (O(n) space) instead of relinking in place.
02. Step 1: in-place reversal—save nxt before turning the arrow
Examine one node cur midway through reversing 10 -> 20 -> 30 -> 40 -> None. Suppose prev heads the already-reversed prefix 10 -> None, and cur sits at 20. Before redirecting cur.next = prev, ask what variable still points to 30 -> 40. Only cur.next! Therefore, every loop iteration must run four assignments in strict order: (1) nxt = cur.next to keep a handle on the unreversed suffix, (2) cur.next = prev to flip the arrow backward, (3) prev = cur to advance the reversed head, and (4) cur = nxt to move to the saved suffix.
Trace all iterations on [10, 20, 30]:
- Start:
prev = None,cur = 10 -> 20 -> 30 -> None. - Pass 1:
nxt = 20,10.next = None,prev = 10,cur = 20. - Pass 2:
nxt = 30,20.next = 10,prev = 20,cur = 30. - Pass 3:
nxt = None,30.next = 20,prev = 30,cur = None(loop exits, returns30 -> 20 -> 10 -> None).
Notice that reverse_list needs no sentinel node because prev begins at None, which immediately becomes the new tail's .next. On an empty input None, the loop executes zero times and returns None; on a 1-node list [99], one pass sets 99.next = None and returns 99.
Before: None <--- [10] [20] ---> [30] ---> [40] ---> None
^ ^ ^
prev cur nxt = cur.next
After: None <--- [10] <--- [20] [30] ---> [40] ---> None
^ ^
prev cur (= nxt)from dataclasses import dataclass
@dataclass(eq=False)
class Node:
val: int
next: "Node | None" = None
def from_list(vals: list[int]) -> Node | None:
dummy = tail = Node(0)
for v in vals:
tail.next = Node(v)
tail = tail.next
return dummy.next
def to_list(head: Node | None) -> list[int]:
out: list[int] = []
cur = head
while cur is not None:
out.append(cur.val)
cur = cur.next
return out
def reverse_list(head: Node | None) -> Node | None:
prev: Node | None = None
cur = head
while cur is not None:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
return prev
print("reversed 4:", to_list(reverse_list(from_list([10, 20, 30, 40]))))
print("reversed 1:", to_list(reverse_list(from_list([99]))))
print("reversed 0:", to_list(reverse_list(None)))reversed 4: [40, 30, 20, 10]
reversed 1: [99]
reversed 0: []03. Step 2: sorted merge with a stack-local sentinel and stability
To merge two sorted singly linked lists a and b in O(len(a) + len(b)) time and O(1) auxiliary space, allocate one stack-local dummy node dummy = tail = Node(0). Because tail starts at dummy, appending the first chosen node via tail.next uses the exact same code path as appending the tenth—there is no if out_head is None: check—and returning dummy.next discards the dummy node cleanly.
Inside while a is not None and b is not None:, compare a.val <= b.val. Using <= rather than strict < preserves stability: when a and b hold nodes with equal keys, taking from a first keeps elements from the left input ahead of tied elements from the right input—vital whenever nodes carry satellite fields such as tag or timestamps. As soon as either a or b hits None, the loop exits and tail.next = a if a is not None else b attaches the entire remaining suffix in O(1) because that suffix is already sorted and linked.
Predict before running: in the tagged merge below, left has (4, "a2") and right has (4, "b2"). In what order do "a2" and "b2" appear in the output, and why does merge_sorted allocate zero new nodes besides dummy?
from dataclasses import dataclass
@dataclass(eq=False)
class TagNode:
val: int
tag: str = ""
next: "TagNode | None" = None
def to_pairs(head: TagNode | None) -> list[tuple[int, str]]:
out: list[tuple[int, str]] = []
cur = head
while cur is not None:
out.append((cur.val, cur.tag))
cur = cur.next
return out
def merge_sorted(a: TagNode | None, b: TagNode | None) -> TagNode | None:
dummy = tail = TagNode(0)
while a is not None and b is not None:
if a.val <= b.val:
tail.next, a = a, a.next
else:
tail.next, b = b, b.next
tail = tail.next
tail.next = a if a is not None else b
return dummy.next
left = TagNode(1, "a1", TagNode(4, "a2"))
right = TagNode(2, "b1", TagNode(4, "b2", TagNode(5, "b3")))
print("merged:", to_pairs(merge_sorted(left, right)))merged: [(1, 'a1'), (2, 'b1'), (4, 'a2'), (4, 'b2'), (5, 'b3')]04. Step 3: splitting at the first middle without infinite recursion
To split a list into two halves for merge sort, we need slow to stop at the last node of the first half (mid), even when the length is even. Initialise slow = head and fast = head.next, then advance slow = slow.next and fast = fast.next.next while fast is not None and fast.next is not None. Why start fast = head.next instead of fast = head? Trace [10, 20]: with fast = head, one step moves slow to 20 and fast past 20 to None, splitting [10, 20] into ([10, 20], []). Because the left half did not shrink, recursive merge sort calls itself on [10, 20] forever until RecursionError! Starting fast = head.next stops the loop immediately on [10, 20], leaving slow at 10 and splitting cleanly into ([10], [20]).
Once slow reaches mid, always save second = slow.next before severing slow.next = None. Clearing slow.next = None first would throw away the only reference to the right half; omitting slow.next = None would leave the first half connected into the second half.
When NOT to use linked-list merge sort: on in-memory Python data, copying node values into a list and running list.sort() (Timsort in C) is expected to run faster because contiguous arrays avoid pointer-chasing cache misses (not measured here); in-place linked merge sort mainly earns its keep when nodes already live in a linked structure and cannot be copied into an array.
Loop stops: [10] ---> [20] ---> [30] ---> [40] ---> None
^ ^
slow fast (fast.next is None)
Save second = slow.next ([30]), then set slow.next = None:
Left: [10] ---> [20] ---> None Right: [30] ---> [40] ---> Nonefrom dataclasses import dataclass
@dataclass(eq=False)
class Node:
val: int
next: "Node | None" = None
def from_list(vals: list[int]) -> Node | None:
dummy = tail = Node(0)
for v in vals:
tail.next = Node(v)
tail = tail.next
return dummy.next
def to_list(head: Node | None) -> list[int]:
out: list[int] = []
cur = head
while cur is not None:
out.append(cur.val)
cur = cur.next
return out
def split_middle(head: Node | None) -> tuple[Node | None, Node | None]:
if head is None or head.next is None:
return head, None
slow: Node = head
fast: Node | None = head.next
while fast is not None and fast.next is not None:
assert slow.next is not None
slow = slow.next
fast = fast.next.next
second = slow.next
slow.next = None
return head, second
for sample in ([10, 20, 30, 40, 50], [10, 20], [10]):
a, b = split_middle(from_list(sample))
print(f"split {sample}:", to_list(a), to_list(b))split [10, 20, 30, 40, 50]: [10, 20, 30] [40, 50]
split [10, 20]: [10] [20]
split [10]: [10] []05. Check your understanding
06. Apply it
Combine split_middle and merge_sorted to build sort_linked_list(head: Node | None) -> Node | None (top-down merge sort in O(n log n) time and O(log n) call-stack space), keeping the base case if head is None or head.next is None: return head. Write a Hypothesis test asserting to_list(sort_linked_list(from_list(xs))) == sorted(xs) across lists including [], [1], [2, 1], and duplicates.
Next, examine fast-and-slow pointers, cycle detection, k-th from end, and list intersection in Two Speeds Through One List.
07. Review prompt
Without looking back:
- Sketch the four pointer steps inside
reverse_listand explain whyprevmust start asNonerather thanhead. - Why does
merge_sortedfinish withtail.next = a if a is not None else binstead of anotherwhileloop? - Why must
split_middleinitialisefast = head.nextrather thanfast = headwhen splitting a 2-node list for merge sort?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.