Cover image for Classic 150 Interview Questions P25 Reverse Nodes in k-Group

Classic 150 Interview Questions P25 Reverse Nodes in k-Group


Timeline

timeline

2025-11-20

init

linked list

Title:

In linked list problems, you generally cannot directly change the value of nodes.

Use head insertion to reverse the linked list. Create a dummy head node pointing to the first node of the first group. But when reaching the second group, use the tail node of the first group as the dummy head node. Otherwise, reversing the second group will break the connection between the last node of the first group and the first node of the second group.

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
struct ListNode {
int val;
ListNode *next;
ListNode()
: val(0)
, next(nullptr)
{
}
ListNode(int x)
: val(x)
, next(nullptr)
{
}
ListNode(int x, ListNode *next)
: val(x)
, next(next)
{
}
};

class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k)
{
int i, j;
ListNode *virt_head = new ListNode(0, head);
ListNode *group_tail;
ListNode *res = head;
ListNode *tmp, *p;

for (i = 0; virt_head->next != nullptr; i++) {
p = virt_head;
group_tail = virt_head->next; //The predecessor of the next group after reversal
// Starting from virt_head, go forward k nodes
for (j = 0; j < k && p != nullptr; j++) {
p = p->next;
}

if (p == nullptr) { // The last group has less than k nodes
break;
}

while (virt_head->next != p) {
tmp = virt_head->next;
virt_head->next = tmp->next;
tmp->next = p->next;
p->next = tmp;
}
if (i == 0) {
res = virt_head->next;
delete virt_head;
}
virt_head = group_tail;
}

return res;
}
};

leetcode hot 100 rewrite:

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
37
38
39
40
41
42
43
44
45
46
47
class Solution {
private:
ListNode *reverse_list(ListNode *head_prev, ListNode *tail_next)
{
ListNode *head = head_prev->next;
ListNode *prev = tail_next, *curr = head, *next;

while (curr != tail_next) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head_prev->next = prev;
return head; // next prev
}

public:
ListNode *reverseKGroup(ListNode *head, int k)
{
if (head == nullptr || k <= 1)
return head;

int i;
ListNode *virtual_head = new ListNode(0, head);
ListNode *head_prev = virtual_head; // The node before the first node
ListNode *tail_next = head; // The node after the last node

while (tail_next != nullptr) {
for (i = 0; i < k; i++) {
if (tail_next != nullptr)
tail_next = tail_next->next;
else
break;
}
if (i != k) // less than k
break;

head_prev = reverse_list(head_prev, tail_next);
tail_next = head_prev->next;
}

head = virtual_head->next;
delete virtual_head;
return head;
}
};