Reorder List
Reorder a linked list to first, last, second, second last and so on, by splitting it, reversing the back half and weaving.
A singly linked list is a chain of nodes, where each node holds a value and a link to the next node. Given head
Example 1
Output: [1, 4, 2, 3]
Example 2
Output: [1, 5, 2, 4, 3]
The Idea
Think of five cards, numbered 1 to 5, laid out in a row. To put them in the new order, you take the first card, then the last, then the second, then the second last, closing in from both ends. For Example 2 that gives 1, 5, 2, 4, and finally 3, the card left in the middle.
On a table, the last card is easy to reach. In a linked list it is not. Each node knows only the node after it, so reaching 5 means walking from 1 through every node. Next we need 4, and node 5 has no link back to it, so we would walk from the start again. Doing that for every node from the back adds up quickly as the list grows. How can we read the back of the list without walking it again and again?
Look at the nodes that come from the back: 5, then 4. They are the second half of the list, 4 and 5, read backwards. So if we turn the second half around, so that 5 points to 4, both halves can be read from front to back. The new order is then simply one node from each half in turn. Look at the picture below.
In the row labelled 1. split, the list is cut after its middle node, 3, into a first half 1, 2, 3 and a second half 4, 5. In the row labelled 2. reverse, the second half now reads 5, 4. In the row labelled 3. weave, the nodes are taken one from each half in turn, starting with the first half: 1, 5, 2, 4, 3.
With five nodes, the first half has one node more than the second, and that node, 3, ends up last. With four nodes, as in Example 1, the halves are 1, 2 and 3, 4. Reversed, the second half reads 4, 3, and weaving 1, 2 with 4, 3 gives 1, 4, 2, 3.
Solution Approach
Copying the nodes into an array would be simpler, so it is worth asking why not. Without a copy, the idea needs three decisions: how to find the middle, how to reverse the second half, and how to weave the two halves together.
Copying the nodes into a list
Why not put every node into an ArrayList
Finding the middle
How do we find the middle without counting the nodes first? Two markers start at headslowfastfastslow
Which node counts as the middle when the length is even? The loop goes on only while fastfast.next != null && fast.next.next != nullslow
Reversing the second half
The second half starts at the node after slowprevnullprev
The first half also needs an end. Setting slow.next = null
Weaving the two halves
How are the halves joined? Keep one marker in each half, firstsecondfirstsecondsecondfirst
Java Solution
The method reorderList
- First, return at once if
ishead or has no next node, since an empty list or a single node is already in order.null - Find the middle with two markers,
andslow , both starting atfast . A loop moveshead one node andslow two nodes, whilefast andfast.next are both notfast.next.next .null - Reverse the nodes after
with the helperslow , and keep the start of the reversed half inreverse(slow.next) . Inside the helper, a loop turns each link around usingsecond andprev , and returnsnext , the old last node.prev - Cut the list in two with
.slow.next = null - Weave with a second loop.
starts atfirst . Whilehead is notsecond , savenull andn1 = first.next , linkn2 = second.next andfirst.next = second , then movesecond.next = n1 tofirst andn1 tosecond .n2
The class also has a small ListNodebuildshowmain
public class ReorderList {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public static void reorderList(ListNode head) {
if (head == null || head.next == null) {
return; // nothing to reorder
}
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next; // one step
fast = fast.next.next; // two steps
}
ListNode second = reverse(slow.next); // second half, back to front
slow.next = null; // cut: the first half ends at slow
ListNode first = head;
while (second != null) { // weave: one node from each half
ListNode n1 = first.next;
ListNode n2 = second.next;
first.next = second;
second.next = n1;
first = n1;
second = n2;
}
}
private static ListNode reverse(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode next = head.next;
head.next = prev; // turn this link around
prev = head;
head = next;
}
return prev; // the old last node
}
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();
}
static void run(int... values) {
ListNode head = build(values);
String before = show(head);
reorderList(head);
System.out.println(before + " -> " + show(head));
}
public static void main(String[] args) {
run(1, 2, 3, 4);
run(1, 2, 3, 4, 5);
run(1, 2, 3);
run(1, 2);
run(1);
run();
}
}
Running it prints:
[1, 2, 3, 4] -> [1, 4, 2, 3]
[1, 2, 3, 4, 5] -> [1, 5, 2, 4, 3]
[1, 2, 3] -> [1, 3, 2]
[1, 2] -> [1, 2]
[1] -> [1]
[] -> []
The line for [1, 2, 3, 4, 5][1, 5, 2, 4, 3][1, 2, 3] -> [1, 3, 2]slow[1, 2] -> [1, 2]slow
What if the cut, slow.next = null[1, 2, 3, 4]n1second.next = n1
Complexity
Finding the middle, reversing and weaving each take about one round per node of half the list, and no node is copied.
- Time: O(n) for a list of n nodes, because
reaches the end in about n / 2 rounds, the reversal visits each node of the second half once, and the weaving does one round per node of that half.fast - Space: O(1). The nodes are relinked where they are, and the method keeps only a few markers such as
,slow ,fast ,first andsecond , however long the list is. Copying the nodes into anprev would take O(n) extra space instead.ArrayList
Finding the middle and reversing the second half also solve