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 leftrightleft ≤ rightleftright
Example 1
Output: [1, 4, 3, 2, 5]
Example 2
Output: [5]
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
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 beforefirstfirstbefore
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 firstbefore
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 beforenextleft - 1left
The fix is an extra node placed in front of the head, whose nextleft - 1beforenext
Which links one move changes
What exactly happens to the links in one move? Give the node right after firstmovedfirstmovedmovedbeforemoved
The order matters because each change reads a link that a later change overwrites. before.nextmovedmoved
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 + 1firstright - leftleftright
Java Solution
The method reverseBetween
- First, create
, a node whosedummy isnext , and starthead on it.before - A first loop moves
forwardbefore times, so it stops on the node just before the range.left - 1 - Set
tofirst , the first node of the range.before.next - A second loop runs
times. Each time it takesright - left , the node aftermoved , closes the gap withfirst , and putsfirst.next = moved.next at the front of the range withmoved andmoved.next = before.next .before.next = moved - Return
, the head of the changed list.dummy.next
Around the method, a small ListNodebuildshowmain
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:
[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][5][3, 2, 1, 4, 5]beforedummy.next
On the fourth line, [1, 2, 5, 4, 3][5, 4, 3, 2, 1]leftright
The bound of the second loop is easy to get wrong by one. With i <= right - left[1, 5, 4, 3, 2]NullPointerException
Complexity
The work is one walk to beforefirst
- Time: O(n) for a list of n nodes: the first loop takes
steps and the second makesleft - 1 moves of three link changes each, so together they touch fewer than n nodes, in a single pass.right - left - Space: O(1). The moves relink the nodes the list already has. The only new node is
, plus a few variables, whatever the length of the list.dummy
Doing the same for every block of k nodes is