Reverse Linked List II

Reverse only the nodes between two positions of a linked list, in one pass, by moving each one to the front of that part.

Given the head of a singly linked list, where each node links only to the node after it, and two positions left and right with left ≤ right, reverse only the nodes from position left to position right. Positions count from 1, so the head is position 1. Return the head of the changed list.

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

The Idea

Think of a toy train with five carriages, numbered 1 to 5, each hooked to the one behind it. Example 1 asks us to turn the middle carriages, 2 to 4, around, so the train reads 1, 4, 3, 2, 5. Carriages 1 and 5 stay where they are.

A linked list is built the same way. Each node holds a value and a link, called next, to the node after it. The first node is the head, and a node can be reached only by starting at the head and following the links.

Turning the middle around is not the whole job. Node 1, just before the range, must end up linked to 4, the new front of the range. Node 2, the old front, must end up linked to 5, the first node after the range. How do we reverse the middle and get both of those joins right, without losing hold of any node?

One way keeps the chain whole at every moment. Call the node just before the range before, here node 1, and the first node of the range first, here node 2. Now take the node right after first, unhook it, and hook it in right after before. Look at the picture below.

The list 1, 2, 3, 4, 5 with the range from left = 2 to right = 4 shaded. before is node 1 and first is node 2. Move 1 takes 3 to the front of the range: 1, 3, 2, 4, 5. Move 2 takes 4 to the front: 1, 4, 3, 2, 5.

In the row labelled start, the shaded range holds 2, 3 and 4. In the row labelled move 1, node 3 has gone to the front of the range, and the list reads 1, 3, 2, 4, 5. In the row labelled move 2, node 4 goes to the front in the same way, and the list reads 1, 4, 3, 2, 5, which is the answer.

Follow node 2, marked first, down the rows. It never moves itself. The other nodes are pulled in front of it, so it slides to the back of the range and stays linked to 5. Node 1, marked before, always links to the current front. So both joins are correct after every move, and a range of three nodes needs only two moves.

Solution Approach

Turning that idea into code means settling three things: how to reach the node before the range, which links one move changes, and how many moves to make.

Reaching the node before the range

How do we get to before? Start at the head and follow next until reaching position left - 1. That breaks down when left is 1, because nothing comes before the head.

The fix is an extra node placed in front of the head, whose next is the head. Such a placeholder is called a dummy node. Starting from it, left - 1 steps always land on the node before the range, and zero steps leave before on the dummy node itself. At the end, the dummy node's next is the head of the changed list, even when the range started at the old head.

Which links one move changes

What exactly happens to the links in one move? Give the node right after first the name moved. Three links change, in this order. first links past moved to the node after it, which closes the gap. moved links to the current front of the range. Then before links to moved.

The order matters because each change reads a link that a later change overwrites. before.next still names the old front when moved is linked to it, and only then is it pointed at moved.

A simpler way also exists: copy the values of the range into an array, reverse the array, and write the values back. It gives the same list, but it needs an extra array as long as the range and changes the values instead of the links. Moving nodes needs nothing extra.

How many moves to make

How many moves does a range need? It holds right - left + 1 nodes. Every node except first is moved once, so the count is right - left. In Example 2, left and right are both 1, so no move happens and the list comes back as it was.

Java Solution

The method reverseBetween works in these steps:

  1. First, create dummy, a node whose next is head, and start before on it.
  2. A first loop moves before forward left - 1 times, so it stops on the node just before the range.
  3. Set first to before.next, the first node of the range.
  4. A second loop runs right - left times. Each time it takes moved, the node after first, closes the gap with first.next = moved.next, and puts moved at the front of the range with moved.next = before.next and before.next = moved.
  5. Return dummy.next, the head of the changed list.

Around the method, a small ListNode class holds one node, build makes a list from numbers, and show prints a list in brackets. The main method runs both examples, then ranges that start at the head, end at the last node, cover the whole list, and hold one node.

Java
public class ReverseLinkedListII {

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public static ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode dummy = new ListNode(0, head);
        ListNode before = dummy;                 // the node just before position left
        for (int i = 1; i < left; i++) {
            before = before.next;
        }
        ListNode first = before.next;            // stays in place, ends up last in the range
        for (int i = 0; i < right - left; i++) {
            ListNode moved = first.next;         // take the node after first
            first.next = moved.next;             // close the gap it leaves
            moved.next = before.next;            // and insert it right after before
            before.next = moved;
        }
        return dummy.next;
    }

    static ListNode build(int... values) {
        ListNode head = null;
        for (int i = values.length - 1; i >= 0; i--) {
            head = new ListNode(values[i], head);
        }
        return head;
    }

    static String show(ListNode node) {
        StringBuilder sb = new StringBuilder("[");
        for (; node != null; node = node.next) {
            sb.append(node.val).append(node.next != null ? ", " : "");
        }
        return sb.append("]").toString();
    }

    public static void main(String[] args) {
        System.out.println(show(reverseBetween(build(1, 2, 3, 4, 5), 2, 4)));
        System.out.println(show(reverseBetween(build(5), 1, 1)));
        System.out.println(show(reverseBetween(build(1, 2, 3, 4, 5), 1, 3)));
        System.out.println(show(reverseBetween(build(1, 2, 3, 4, 5), 3, 5)));
        System.out.println(show(reverseBetween(build(1, 2, 3, 4, 5), 1, 5)));
        System.out.println(show(reverseBetween(build(1, 2, 3, 4, 5), 3, 3)));
    }
}

Running it prints:

Output
[1, 4, 3, 2, 5]
[5]
[3, 2, 1, 4, 5]
[1, 2, 5, 4, 3]
[5, 4, 3, 2, 1]
[1, 2, 3, 4, 5]

Example 1 gives [1, 4, 3, 2, 5], the same list as the row labelled move 2, and Example 2 gives back [5] with no move made. Look at the third line, [3, 2, 1, 4, 5], from the range 1 to 3. There, before never leaves the dummy node, and the new head, 3, comes back through dummy.next.

On the fourth line, [1, 2, 5, 4, 3], the range runs to the last node, so node 3 ends up last in the whole list with nothing after it. The fifth line turns the whole list into [5, 4, 3, 2, 1]. The last line is unchanged, because left and right are both 3.

The bound of the second loop is easy to get wrong by one. With i <= right - left, the loop makes one move too many. Example 1 then pulls 5 into the range and returns [1, 5, 4, 3, 2]. Example 2 stops with a NullPointerException, because node 5 has no node after it to move.

Complexity

The work is one walk to before plus one move for every node of the range after first.

  • Time: O(n) for a list of n nodes: the first loop takes left - 1 steps and the second makes right - left moves of three link changes each, so together they touch fewer than n nodes, in a single pass.
  • Space: O(1). The moves relink the nodes the list already has. The only new node is dummy, plus a few variables, whatever the length of the list.

Doing the same for every block of k nodes is Reverse Nodes in k-Group.