[LeetCode] Reverse Nodes in k-Group

25. Reverse Nodes in k-Group

Given the head of a linked list, reverse the nodes of the list k at a time, and return the 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.

You may not alter the values in the list’s nodes, only nodes themselves may be changed.

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
/**
* Definition for singly-linked list.
* 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) {
if(!head) return nullptr;
int n = k;
ListNode* dummy = new ListNode();
ListNode* tmp;
ListNode* tail = head;
while(n--) {
tmp = head->next;
head->next = dummy->next;
dummy->next = head;
head = tmp;
if(!head && n) {
return reverseKGroup(dummy->next, k - n);
}
}
if(tmp) {
tail->next = reverseKGroup(tmp, k);
}
return dummy->next;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/07/PS/LeetCode/reverse-nodes-in-k-group/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.