Reference: LeetCode EPI 7.2
Difficulty: Hard

Problem

Given a linked list, reverse the nodes of a linked list $k$ at a time and return its modified list.

$k$ is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of $k$ then left-out nodes in the end should remain as it is.

Note:

  • Only constant extra memory $O(1)$ is allowed.
  • You may not alter the values in the list’s nodes, only nodes itself may be changed.

Example:

1
2
3
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5

Analysis

Iteration

Calculate how many groups should be reversed. Reverse each group’s nodes.

1
2
3
4
5
6
7
8
9
10
//       1   2   3   4   5    k =3
// prev p nH rest
// 2 1 3 4 5
// prev nH p rest
// 2 1 3 4 5
// prev p nH rest
// 3 2 1 4 5
// prev nH p rest
// 3 2 1 4 5
// prev p
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null) {
return null;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
int len = getLength(head);
// reverse groups
ListNode prev = dummy;
ListNode p = head;

for (int i = 0; i < len / k; ++i) {
int count = k;
while (count > 1) { // k = 3, and need to do 2 times
ListNode newHead = p.next;
ListNode rest = p.next.next;
p.next = rest; // set the tail to rest
newHead.next = prev.next; // not "p"
prev.next = newHead;
// no need to update p
--count;
}
prev = p; // set prev as the new group dummy
p = p.next; // go to next group
}
return dummy.next;
}

private int getLength(ListNode head) {
int len = 0;
while (head != null) {
++len;
head = head.next;
}
return len;
}

Time: $O(N)$
Space: $O(1)$