Rotate List
Move the last k nodes of a linked list to its front, by counting the nodes and rewiring two links.
Given the head of a linked list and a number kkk
Example 1
Output: [4, 5, 1, 2, 3]
Example 2
Output: [2, 0, 1]
Explanation: 4 rotations of 3 nodes equal 1 rotation.
The Idea
Think of five people, numbered 1 to 5, standing in a line, and the last one walks to the front. Do that twice and the line reads 5, 1, 2, 3, 4, then 4, 5, 1, 2, 3, the answer to Example 1. In a linked list, each item is a node: a box holding a number and a link to the next node. The list only knows its first node, the head.
Example 2 rotates a list of three nodes four times. Three rotations bring 0, 1, 2 all the way round to where it started, so only the fourth one changes anything. A list of n nodes repeats every n rotations, which means only the remainder of k
Even so, moving one node at a time means a trip to the end of the list for every rotation. Is there a quicker way? Look at the two lists in Example 1 side by side: the last two nodes, 4 and 5, moved to the front as one block, and the rest, 1, 2, 3, followed them unchanged. So a rotation by k
In the row labelled before, node 1 is the old head and node 5 is the old tail, the last node. The link from 3 to 4 is cut, so 4 becomes the new head and 3 the new tail. The curved arrow labelled new link joins the old tail, 5, to the old head, 1. Read the row labelled after from the left and you get 4, 5, 1, 2, 3.
So the whole rotation changes only two links, wherever the cut falls. The work is in finding the right places: the old tail, and the node where the cut goes.
Solution Approach
Turning that idea into code means settling two things: how to make a huge k
Moving one node at a time
Why not simply repeat the rotation kk
Reducing k
How do we get rid of the extra full turns? Count the nodes first, and call the count n. Since n rotations give back the same list, k % nk
The walk that counts the nodes ends on the last node, so the same walk also finds the old tail. Nothing has to be walked twice for it.
Finding the new tail
Where does the cut go? The last k
Java Solution
The method rotateRight
- First, an empty list (
ishead ) has nothing to rotate, so returnnull .null - Walk a pointer named
from the head to the last node, counting the nodes intail on the way. When the loop stops,n is on the old tail.tail - Reduce
withk . If it is now 0, returnk %= n unchanged.head - Start a second pointer,
, at the head, and a loop moves it forward until it stands on node number n - k.newTail - Keep the node after it in
. Then cut the list by settingnewHead tonewTail.next , and join the old tail to the old head withnull .tail.next = head - Return
.newHead
The class also has a small ListNodebuildshowmainkk
public class RotateList {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public static ListNode rotateRight(ListNode head, int k) {
if (head == null) {
return null;
}
int n = 1;
ListNode tail = head;
while (tail.next != null) { // count the nodes and stop on the last one
tail = tail.next;
n++;
}
k %= n; // every n rotations give the same list back
if (k == 0) {
return head;
}
ListNode newTail = head;
for (int i = 1; i < n - k; i++) { // walk to node number n - k
newTail = newTail.next;
}
ListNode newHead = newTail.next;
newTail.next = null; // cut the list after the new tail
tail.next = head; // the old tail now leads to the old head
return newHead;
}
static ListNode build(int... values) {
ListNode dummy = new ListNode(0);
ListNode last = dummy;
for (int v : values) {
last.next = new ListNode(v);
last = last.next;
}
return dummy.next;
}
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(rotateRight(build(1, 2, 3, 4, 5), 2)));
System.out.println(show(rotateRight(build(0, 1, 2), 4)));
System.out.println(show(rotateRight(build(1, 2, 3, 4, 5), 5)));
System.out.println(show(rotateRight(build(1, 2, 3, 4, 5), 2000000002)));
System.out.println(show(rotateRight(build(7), 3)));
System.out.println(show(rotateRight(build(), 1)));
}
}
Running it prints:
[4, 5, 1, 2, 3]
[2, 0, 1]
[1, 2, 3, 4, 5]
[4, 5, 1, 2, 3]
[7]
[]
Example 1 comes out as [4, 5, 1, 2, 3][2, 0, 1][1, 2, 3, 4, 5]
The fourth line rotates the same five nodes by 2,000,000,002. The remainder 2,000,000,002 % 5 is 2, so the result is [4, 5, 1, 2, 3][7][]
The line k %= n[1, 2, 0][2, 3, 4, 5, 1]k
Complexity
The work is two walks from the head: one to the old tail, and one to the new tail.
- Time: O(n), for a list of n nodes: the first walk visits every node once to count them, and the second stops at node n - k, before the end. Because of
, a hugek %= n adds no steps.k - Space: O(1). No node is copied. The method keeps three pointers and a count, and changes only two links,
andnewTail.next .tail.next
The same rotation on an array, where elements cannot be relinked, is