Reverse Nodes in k-Group
Reverse a linked list k nodes at a time by moving each group's nodes to its front, and leave a short tail as it is.
Given the head of a singly linked list, where each node links only to the node after it, and a positive whole number kkkkk
Example 1
Output: [2, 1, 4, 3, 5]
Example 2
Output: [3, 2, 1, 4, 5]
The Idea
Picture five cards in a row, numbered 1 to 5. Example 1 takes them two at a time and flips each pair: 1, 2 becomes 2, 1, and 3, 4 becomes 4, 3. Card 5 has no partner, so it stays at the end, and the row reads 2, 1, 4, 3, 5. Example 2 flips three at a time: 1, 2, 3 becomes 3, 2, 1, and the two cards left over, 4 and 5, are too few for a group.
A linked list is built like a chain of those cards. In a linked list, every node stores one value plus next
Reversing the nodes inside a group is only half the job. After the first group of Example 1 becomes 2, 1, the list must start at 2, and node 1 must link to 3, the start of the next group. When that next group becomes 4, 3, node 1's link has to change again, to 4. How do we keep track of where each group hangs on to the rest of the list?
Keep a marker on the node just before the current group, and call it beforenext
In the row labelled start, beforebefore
In the row labelled after group 2, the list reads 2, 1, 4, 3, 5, and beforek = 2
So the whole job is one round per group, each starting from beforekbefore
Solution Approach
Turning that idea into code means settling three things: how to tell whether a full group is left, how to reverse one group in place, and where before
Checking for a full group
How do we know that kbeforecheckbeforeknextnullchecknullkk
The check comes before any relinking. If we started reversing and ran out of nodes halfway, as with 4 and 5 in Example 2, we would have to undo those moves to leave the short tail in order.
Reversing one group in place
How do we reverse kfirstmovedbefore
Three links change, in this order. first.next = moved.nextmovedmoved.next = before.nextmovedbefore.next = moved
In group 1 of Example 1, one move takes node 2 to the front, and the group reads 2, 1. With k = 3firstk - 1
Notice that first
A simpler way would copy the values into an array, reverse each block of k
Moving on to the next group
Where does beforefirstbefore = first
Java Solution
The method reverseKGroup
- First, create
, a node whosedummy isnext , and starthead on it.before - A
loop handles one group per round. Inside it, a firstwhile (true) loop movesfor fromcheck up tobefore steps forward. Ifk becomescheck , fewer thannull nodes are left, and the method returnsk , the head of the changed list.dummy.next - Set
tofirst , the first node of the group.before.next - A second
loop runsfor times. Each time it takesk - 1 , the node aftermoved , closes the gap withfirst , and putsfirst.next = moved.next at the front of the group withmoved andmoved.next = before.next .before.next = moved - Set
tobefore , now the group's last node, and start the next round.first
Around the method, a small ListNodebuildshowmainkk = 1k
public class ReverseNodesInKGroup {
static class ListNode {
int val;
ListNode next;
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public static ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(0, head);
ListNode before = dummy; // the node just before the current group
while (true) {
ListNode check = before;
for (int i = 0; i < k; i++) { // are there k nodes left?
check = check.next;
if (check == null) {
return dummy.next; // fewer than k: leave them as they are
}
}
ListNode first = before.next; // stays in place, ends up last in the group
for (int i = 0; i < k - 1; 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;
}
before = first; // the node just before the next group
}
}
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(reverseKGroup(build(1, 2, 3, 4, 5), 2)));
System.out.println(show(reverseKGroup(build(1, 2, 3, 4, 5), 3)));
System.out.println(show(reverseKGroup(build(1, 2, 3, 4, 5, 6), 3)));
System.out.println(show(reverseKGroup(build(1, 2, 3, 4, 5), 5)));
System.out.println(show(reverseKGroup(build(1, 2, 3, 4, 5), 1)));
System.out.println(show(reverseKGroup(build(1, 2, 3), 4)));
}
}
Running it prints:
[2, 1, 4, 3, 5]
[3, 2, 1, 4, 5]
[3, 2, 1, 6, 5, 4]
[5, 4, 3, 2, 1]
[1, 2, 3, 4, 5]
[1, 2, 3]
Example 1 gives [2, 1, 4, 3, 5][3, 2, 1, 4, 5][3, 2, 1, 6, 5, 4]check
With k = 5[5, 4, 3, 2, 1]k = 1[1, 2, 3]k = 4checknull
The line before = firstbefore = before.nextbefore[2, 3, 4, 5, 1][3, 4, 5, 2, 1]
Complexity
Each round walks check
- Time: O(n) for a list of n nodes:
passes each node once, in the round of its group or in the last round over the short tail, and the second loop moves each node at most once, with three link changes.check - Space: O(1). The groups are relinked in place. The only new node is
, plus a few variables, and there is no recursion whose calls would pile up with the length of the list.dummy
With k = 2