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, the first node of such a list L0 → L1 → ... → Ln, reorder it to L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → ... The change is made in place: only the links between the nodes may change, not the values stored in them, and the method returns nothing.

Example 1
Input: head = [1, 2, 3, 4]
Output: [1, 4, 2, 3]
Example 2
Input: head = [1, 2, 3, 4, 5]
Output: [1, 5, 2, 4, 3]
Solution

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.

Reordering the list 1, 2, 3, 4, 5. First the list is cut after its middle node, 3, into a first half 1, 2, 3 and a second half 4, 5. Then the second half is reversed to 5, 4. Then the halves are woven, one node from each in turn: 1, 5, 2, 4, 3.

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, Java's resizable array, first? Then the last node is just the last entry. Two indexes, one moving forward from the start and one moving back from the end, can relink the nodes in the new order. That works, but the copy takes extra memory that grows with the list. Splitting, reversing and weaving need only a few variables.

Finding the middle

How do we find the middle without counting the nodes first? Two markers start at head: slow moves one node at a time, and fast moves two. When fast can go no further, slow has gone half as far, so it is on the middle node. This pairing of a one-step marker and a two-step marker is usually called the slow and fast pointer technique.

Which node counts as the middle when the length is even? The loop goes on only while fast has two more nodes ahead of it, fast.next != null && fast.next.next != null. For 1, 2, 3, 4 it stops with slow on 2, the first of the two middle nodes, and for 1, 2, 3, 4, 5 on 3. So the first half is never shorter than the second, which the weaving relies on.

Reversing the second half

The second half starts at the node after slow. To reverse it, walk along it and turn each link around, so that each node points to the node before it instead of the one after. A variable prev holds the node before the current one, starting at null. The link to the next node is saved before it is overwritten. When the walk ends, prev is on the old last node, 5, which now starts the reversed half.

The first half also needs an end. Setting slow.next = null removes the link from the middle node into the second half, which is the dashed line labelled cut in the first row of the picture.

Weaving the two halves

How are the halves joined? Keep one marker in each half, first and second. Each round links the node at first to the node at second, and the node at second to the node that used to follow the node at first. Both links get overwritten, so the next node of each half is saved before the round starts. The loop ends when the reversed half runs out. With an odd length, the extra node of the first half is already in place at the end.

Java Solution

The method reorderList works in these steps:

  1. First, return at once if head is null or has no next node, since an empty list or a single node is already in order.
  2. Find the middle with two markers, slow and fast, both starting at head. A loop moves slow one node and fast two nodes, while fast.next and fast.next.next are both not null.
  3. Reverse the nodes after slow with the helper reverse(slow.next), and keep the start of the reversed half in second. Inside the helper, a loop turns each link around using prev and next, and returns prev, the old last node.
  4. Cut the list in two with slow.next = null.
  5. Weave with a second loop. first starts at head. While second is not null, save n1 = first.next and n2 = second.next, link first.next = second and second.next = n1, then move first to n1 and second to n2.

The class also has a small ListNode class and two helpers: build makes a list from numbers, and show prints a list the way the examples write it. The main method runs both examples, then lists of three, two, one and zero nodes.

Java
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:

Output
[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] ends in [1, 5, 2, 4, 3], the row labelled 3. weave in the picture. Look at [1, 2, 3] -> [1, 3, 2]: slow stops on 2, the second half is the single node 3, and weaving puts it between 1 and 2. In [1, 2] -> [1, 2], slow stays on 1, so weaving links 1 to 2, where it already pointed. The lists of one node and of none come back unchanged from the early return.

What if the cut, slow.next = null, is left out? A separate run of the same method without that line turned [1, 2, 3, 4] into a list whose first ten values are 1, 4, 2, 3, 3, 3, 3, 3, 3, 3. Node 2 still links to 3, so in the last round of weaving, n1 is node 3 and second.next = n1 makes node 3 point to itself. The list never ends.

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 fast 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.
  • Space: O(1). The nodes are relinked where they are, and the method keeps only a few markers such as slow, fast, first, second and prev, however long the list is. Copying the nodes into an ArrayList would take O(n) extra space instead.

Finding the middle and reversing the second half also solve Palindrome Linked List, which compares the two halves instead of weaving them.