This lesson is part of the Merge Sort series. Arrays need temporary space to merge efficiently. Linked lists have a different structure: nodes can be joined by changing links, so merge sort is a natural fit.

Follow the animation step by step
The animation uses the linked list 8 → 3 → 5 → 1. Each value sits in a node that points to the next node.
- Start with one chain: follow the links from 8 to 3 to 5 to 1.
- Split at the middle: divide it into 8 → 3 and 5 → 1. The nodes themselves remain; the algorithm changes which links connect them.
- Sort each half: recursively split each two-node chain and merge its single-node pieces. This produces 3 → 8 and 1 → 5.
- Merge by relinking: compare the two head nodes, 3 and 1. Link 1 first, then compare 3 and 5 and link 3, then link 5 and the remaining 8.
- Finish one sorted chain: the links now form 1 → 3 → 5 → 8. No array elements had to shift to make room.

Why merge sort fits a linked list
A linked list can be split by walking to its midpoint. After sorting both halves, merge them by connecting the smaller head node to the result and advancing that list. The operation does not require shifting later elements, as an array insertion would.
The algorithm takes O(n log n) time. A linked-list merge can use O(1) extra node storage when it relinks existing nodes, though recursive splitting uses O(log n) call-stack space. An iterative bottom-up version can avoid that recursion stack.
Merge two sorted lists
Given 1 → 4 → 7 and 2 → 3 → 8, compare the two head nodes each time:
Compare 1 and 2: take 1
Compare 4 and 2: take 2
Compare 4 and 3: take 3
Continue: 1 → 2 → 3 → 4 → 7 → 8A stable merge chooses the node from the left list when keys are equal. This preserves the original order of equal-key records, assuming the split keeps earlier nodes in the left half.
Recursive outline
sort(head):
if head is empty or has one node:
return head
left, right = splitAtMiddle(head)
return merge(sort(left), sort(right))The split must detach the two halves; otherwise, recursive calls can keep seeing the same nodes. A slow and fast pointer is a common way to find the midpoint in one traversal. Pay attention to lists with two nodes, because incorrect stopping conditions can create an empty half or an endless recursion.
Use linked-list merge sort when the input is already represented as linked nodes and stable O(n log n) sorting is required. For arrays, a standard array merge sort is usually easier to access and often more cache-friendly.



