Flattening linked lists
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Flattening means turning a chain whose items each also hold a smaller sorted chain into one single sorted chain. You do it by merging the lists two at a time, which reuses the merge step you already know.
Practical use cases
- Web app: One result list from many shop sections. A marketplace search asks each category section for its matches, and each section returns results already sorted by price. Instead of dumping them together and re-sorting, the results are merged pair by pair into one sorted list. The shopper sees a single price-ordered page.
- Web app: Nested menu or folder to a flat list. A file manager has folders that each contain a sorted list of items, and the user wants a single "all files" view sorted by name. Flattening merges the folder lists into one. The same pattern builds a single dropdown from grouped options.
- System: Merging sorted sources in a search engine. A search service queries several index shards, each returning sorted hits. A merge step combines these lists into one ranked list. It is the same flattening idea scaled up to many lists, and it lets the service answer from many machines while the user still sees one clean ranked page.
The story: The Dabbawala's Tiffin Towers
In Mumbai, a dabbawala collects tiffin carriers from many homes and stacks them in towers. Each tower is sorted by delivery time from top to bottom. The towers themselves stand side by side in a row. Now the train guard says: "I need one line of tiffins in delivery-time order, not many towers!"
In list language, every node has two arrows: next to the tower on its right (only the tower heads use it) and down to the next tiffin in its tower. All the towers are already sorted. Mira asked, "Where have I seen sorted chains being combined?" She remembered merging two sorted queues at the ticket window.
The plan: begin at the last tower and the one before it, merge the two sorted towers into one. Then merge the tower before that into the result, and so on to the left. After each merge the column is longer and still sorted. Each merge only relinks down pointers and clears the sideways links.
This is flattening a linked list (a list with sorted child lists). The merge from the right is naturally recursive: flatten the rest, then merge the current tower into it. It reuses the merge routine and finishes with one sorted down-chain. The cost is about (total number of nodes) × (number of towers) in the worst case, since earlier items can be re-walked by each merge.
How to spot this problem, and where you need it
You have many separate sorted lists, perhaps hanging off a main list, and want a single sorted list without throwing away their order and sorting everything again.
Signs you need it
- The data looks like a list of lists, each already sorted, such as results grouped by shop, shard, folder or day.
- The statement says "flatten" along with sorted, or each node has both a next link and a down link.
- You currently join all the pieces and call a full sort, even though every piece was ordered.
Where to use it in a project
- Combining sorted results from multiple categories, shards or microservices into one page.
- Turning grouped, sorted data such as folders, menus or daily reports into one ordered list.
- Preparing one merged, ordered list so that pagination can show page 1, 2 and 3 correctly.
The solution
Start from the last list and merge it with the one before it using the standard two-sorted-lists merge, using the down links as the chain. Take the merged result and merge it with the list before that. Continue until you reach the first list. The final result is one sorted chain, and the order inside each original list is used rather than recomputed.
Payoff: Before: sorting a joined 100,000-item pile from scratch. After: merging the already ordered pieces, touching each item only a few times.
Explain it like I am 8
Imagine several short, already-sorted stacks of cards standing in a row. Take the last two stacks and zip them into one sorted stack. Then zip in the next stack to the left, and so on, until there is just one big sorted stack.
How it works, step by step
- Each node has
next(sideways to the next column head) anddown(the next item in its own sorted column). - Base case: if there is no column to the right, the list is already flat.
- Flatten the rest first:
rest = flatten(head.next), then cuthead.next = null. - Merge the current column with
restusing the sorted-merge logic, linking throughdown. - Return the merged head. Walk
downfrom it to read the final sorted order.
The code in four languages
PHP
<?php
class Node {
public $val;
public ?Node $next = null; // sideways: next column head
public ?Node $down = null; // downward: next item in this column
public function __construct($val) { $this->val = $val; }
}
// merge two sorted columns, linking through ->down
function mergeDown(?Node $a, ?Node $b): ?Node {
$dummy = new Node(0);
$tail = $dummy;
while ($a !== null && $b !== null) {
if ($a->val <= $b->val) { $tail->down = $a; $a = $a->down; }
else { $tail->down = $b; $b = $b->down; }
$tail = $tail->down;
$tail->next = null; // the result is one single column
}
$tail->down = $a !== null ? $a : $b;
return $dummy->down;
}
function flatten(?Node $head): ?Node {
if ($head === null || $head->next === null) return $head; // nothing to the right
$rest = flatten($head->next); // 1) flatten everything to the right
$head->next = null;
return mergeDown($head, $rest); // 2) merge this column into it
}
// build columns from arrays: [[5,7,8,30], [10,20], ...]
function build(array $columns): ?Node {
$firstHead = null; $prevHead = null;
foreach ($columns as $col) {
$head = null; $prev = null;
foreach ($col as $v) {
$n = new Node($v);
if ($prev === null) { $head = $n; } else { $prev->down = $n; }
$prev = $n;
}
if ($prevHead === null) { $firstHead = $head; } else { $prevHead->next = $head; }
$prevHead = $head;
}
return $firstHead;
}
$flat = flatten(build([[5, 7, 8, 30], [10, 20], [19, 22, 50], [28, 35, 40, 45]]));
$out = [];
for ($c = $flat; $c !== null; $c = $c->down) { $out[] = $c->val; }
echo implode(' ', $out) . "\n"; // 5 7 8 10 19 20 22 28 30 35 40 45 50JavaScript
class Node {
constructor(val) {
this.val = val;
this.next = null; // sideways: next column head
this.down = null; // downward: next item in this column
}
}
// merge two sorted columns, linking through .down
function mergeDown(a, b) {
const dummy = new Node(0);
let tail = dummy;
while (a !== null && b !== null) {
if (a.val <= b.val) { tail.down = a; a = a.down; }
else { tail.down = b; b = b.down; }
tail = tail.down;
tail.next = null; // the result is one single column
}
tail.down = a !== null ? a : b;
return dummy.down;
}
function flatten(head) {
if (head === null || head.next === null) return head; // nothing to the right
const rest = flatten(head.next); // 1) flatten everything to the right
head.next = null;
return mergeDown(head, rest); // 2) merge this column into it
}
// build columns from arrays: [[5,7,8,30], [10,20], ...]
function build(columns) {
let firstHead = null, prevHead = null;
for (const col of columns) {
let head = null, prev = null;
for (const v of col) {
const n = new Node(v);
if (prev === null) head = n; else prev.down = n;
prev = n;
}
if (prevHead === null) firstHead = head; else prevHead.next = head;
prevHead = head;
}
return firstHead;
}
const flat = flatten(build([[5, 7, 8, 30], [10, 20], [19, 22, 50], [28, 35, 40, 45]]));
const out = [];
for (let c = flat; c !== null; c = c.down) out.push(c.val);
console.log(out.join(' ')); // 5 7 8 10 19 20 22 28 30 35 40 45 50Java
import java.util.*;
public class Main {
static class Node {
int val;
Node next; // sideways: next column head
Node down; // downward: next item in this column
Node(int val) { this.val = val; }
}
// merge two sorted columns, linking through .down
static Node mergeDown(Node a, Node b) {
Node dummy = new Node(0);
Node tail = dummy;
while (a != null && b != null) {
if (a.val <= b.val) { tail.down = a; a = a.down; }
else { tail.down = b; b = b.down; }
tail = tail.down;
tail.next = null; // the result is one single column
}
tail.down = (a != null) ? a : b;
return dummy.down;
}
static Node flatten(Node head) {
if (head == null || head.next == null) return head; // nothing to the right
Node rest = flatten(head.next); // 1) flatten everything to the right
head.next = null;
return mergeDown(head, rest); // 2) merge this column into it
}
// build columns from arrays: {{5,7,8,30}, {10,20}, ...}
static Node build(int[][] columns) {
Node firstHead = null, prevHead = null;
for (int[] col : columns) {
Node head = null, prev = null;
for (int v : col) {
Node n = new Node(v);
if (prev == null) head = n; else prev.down = n;
prev = n;
}
if (prevHead == null) firstHead = head; else prevHead.next = head;
prevHead = head;
}
return firstHead;
}
public static void main(String[] args) {
Node flat = flatten(build(new int[][]{{5, 7, 8, 30}, {10, 20}, {19, 22, 50}, {28, 35, 40, 45}}));
StringJoiner out = new StringJoiner(" ");
for (Node c = flat; c != null; c = c.down) out.add(String.valueOf(c.val));
System.out.println(out); // 5 7 8 10 19 20 22 28 30 35 40 45 50
}
}Go
package main
import (
"fmt"
"strings"
)
type Node struct {
val int
next *Node // sideways: next column head
down *Node // downward: next item in this column
}
// mergeDown merges two sorted columns, linking through .down
func mergeDown(a, b *Node) *Node {
dummy := &Node{}
tail := dummy
for a != nil && b != nil {
if a.val <= b.val {
tail.down = a
a = a.down
} else {
tail.down = b
b = b.down
}
tail = tail.down
tail.next = nil // the result is one single column
}
if a != nil {
tail.down = a
} else {
tail.down = b
}
return dummy.down
}
func flatten(head *Node) *Node {
if head == nil || head.next == nil { // nothing to the right
return head
}
rest := flatten(head.next) // 1) flatten everything to the right
head.next = nil
return mergeDown(head, rest) // 2) merge this column into it
}
// build makes columns from slices: [[5,7,8,30], [10,20], ...]
func build(columns [][]int) *Node {
var firstHead, prevHead *Node
for _, col := range columns {
var head, prev *Node
for _, v := range col {
n := &Node{val: v}
if prev == nil {
head = n
} else {
prev.down = n
}
prev = n
}
if prevHead == nil {
firstHead = head
} else {
prevHead.next = head
}
prevHead = head
}
return firstHead
}
func main() {
flat := flatten(build([][]int{{5, 7, 8, 30}, {10, 20}, {19, 22, 50}, {28, 35, 40, 45}}))
var out []string
for c := flat; c != nil; c = c.down {
out = append(out, fmt.Sprint(c.val))
}
fmt.Println(strings.Join(out, " ")) // 5 7 8 10 19 20 22 28 30 35 40 45 50
}Time: O(N × k) worst case · Extra space: O(k). N is the total node count and k the number of columns. The recursion is k deep and every merge relinks nodes without copying them.
Watch out for
- Merging through
nextinstead ofdown, which mixes up the two kinds of links. - Forgetting to clear
nextpointers, so the result still has stray sideways links. - Flattening from the left without first flattening the rest, which makes the merge order messy; the right-to-left fold is the clean way.
Quick check
- What is the main tool used to flatten the lists?
- Reversing the list
- Merging two sorted lists
- Finding the middle
- Detecting a cycle
- Which pointer do we merge along?
- next
- prev
- down
- head
- What do we do right after flattening the rest?
- Merge it into nothing
- Delete the current column
- Reverse it
- Cut head.next and merge the current column into the result