Partition List
Move every node below x to the front of a linked list, keeping the order inside both groups.
Given the head of a linked list and a value xxx
Example 1
Output: [1, 2, 2, 4, 3, 5]
Example 2
Output: [1, 2]
The Idea
Picture a row of numbered cards that you sort into two new rows: cards below 3 in the first row, all other cards in the second. Each card goes at the right end of its row, so each row keeps the cards in the order you met them. Put the first row in front of the second and you have the answer.
Here the cards are the nodes of a linked list. In a linked list, the cards become nodes, and each node points to the one after it through a link called nextnullhead
Walk through Example 1 with x = 3x
With an array, we could copy the values into two new arrays and write them back. A linked list allows something cheaper. A node's place in the list is decided only by which next
We can. Walk the list once, and hook each node onto the end of one of two chains: a small chain for values less than xx
The top row is the list, with each node coloured by the chain it goes to. The row labelled "small chain" holds 1, 2, 2, and the row labelled "big chain" holds 4, 3, 5, each in the order the walk met them. Each chain begins at a dashed box labelled "dummy", a spare node with no real value that only marks where the chain begins. The orange arrow labelled "join the chains" links the last 2 to the 4. The orange arrow after 5 points to null
Solution Approach
Turning that idea into code means settling three things: where each chain starts, how a node is added to the end of a chain, and how the chains are ended and joined. Copying the values is the simple alternative, and it costs more memory.
Where each chain starts
What does a chain look like before its first node arrives? It is empty, and adding the first node to an empty chain would need its own special case. A dummy node avoids that. It is a spare node, created before the walk, that holds no real value and only sits in front of the chain.
The code makes two of them, smallHeadbigHeadsmallHead.nextbigHead.next
Adding a node to the end of a chain
How do we reach the end of a chain without walking along it each time? Keep a pointer to its last node: smallbigsmall.next = nodesmall = node
The walk meets the nodes in their original order and always adds at the end, so each chain keeps that order, as the problem asks. The test is node.val < xx
Ending and joining the chains
Where does the last node of each chain point when the walk ends? Still to its old nextsmall.next = bigHead.next
The big chain's last node is different. In Example 1 it is the 5, and its nextbig.next = nullnull
These two lines also handle a chain that stays empty. With no big nodes, bigHead.nextnullsmallsmallHeadsmallHead.next
Copying the values instead
Would copying be simpler? You could collect the small values and the big values into two lists, then write them back into the nodes in that order. That also takes one pass, but it stores a copy of every value. Relinking the nodes needs only the two dummy nodes, however long the list is.
Java Solution
The method partition
- First, create the two dummy nodes,
andsmallHead , and the two last-node pointers,bigHead andsmall , which start on those dummies.big - Walk the list with a
loop, movingfor fromnode until it ishead . Ifnull is less thannode.val , add the node to the small chain withx andsmall.next = node . Otherwise, add it to the big chain the same way, withsmall = node .big - After the loop, end the big chain with
.big.next = null - Join the chains with
.small.next = bigHead.next - Return
, the first real node of the joined list.smallHead.next
The mainbuildshowxx
public class PartitionList {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public static ListNode partition(ListNode head, int x) {
ListNode smallHead = new ListNode(0); // dummy in front of the "less than x" chain
ListNode bigHead = new ListNode(0); // dummy in front of the "x or more" chain
ListNode small = smallHead; // last node of the small chain so far
ListNode big = bigHead; // last node of the big chain so far
for (ListNode node = head; node != null; node = node.next) {
if (node.val < x) {
small.next = node; // append to the small chain
small = node;
} else {
big.next = node; // append to the big chain
big = node;
}
}
big.next = null; // end the big chain: it may still point back
small.next = bigHead.next; // small chain, then big chain
return smallHead.next;
}
static ListNode build(int... values) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
for (int v : values) {
tail.next = new ListNode(v);
tail = tail.next;
}
return dummy.next;
}
static String show(ListNode head) {
StringBuilder sb = new StringBuilder("[");
for (ListNode n = head; n != null; n = n.next) {
sb.append(n.val).append(n.next != null ? ", " : "");
}
return sb.append("]").toString();
}
public static void main(String[] args) {
System.out.println(show(partition(build(1, 4, 3, 2, 5, 2), 3)));
System.out.println(show(partition(build(2, 1), 2)));
System.out.println(show(partition(build(5, 1, 4, 2, 3), 3)));
System.out.println(show(partition(build(1, 2, 3), 10)));
System.out.println(show(partition(build(7, 8, 9), 1)));
System.out.println(show(partition(build(), 5)));
}
}
Running it prints:
[1, 2, 2, 4, 3, 5]
[1, 2]
[1, 2, 5, 4, 3]
[1, 2, 3]
[7, 8, 9]
[]
The first line matches Example 1, with 4, 3, 5 kept in their original order, and the second line, [1, 2]x[5, 1, 4, 2, 3]x = 3
The next two lines each leave one chain empty. With x = 10nullx = 1[7, 8, 9][]smallHead.nextnull
The line big.next = null1 2 2 4 3 5 2 4 3 5 2 4 3 5 2next
Complexity
The method walks the list once and does a fixed amount of work at each node.
- Time: O(n) for a list of n nodes: the
loop visits each node once, and adding it to a chain takes two pointer assignments, becausefor andsmall already sit at the chain ends.big - Space: O(1). Only the two dummy nodes and a few pointers are new. The existing nodes are relinked, not copied.
Splitting a list by position instead of by value is