Skip to main content

Reverse Nodes in k-Group

Problem

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.

Solution Approach

Click - to see solution code
class Solution {
public:
ListNode* reverseKGroup(ListNode* h, int k) {
ListNode* root;
root = new ListNode(0);
ListNode* tail = root;
tail->next = h;
ListNode* t = h;
auto fun = [&](ListNode* t, ListNode* tail, int k) {
ListNode* h1;
while (1) {
int cnt = 0;
while (t && cnt < k) {
ListNode* temp;
temp = new ListNode(t->val);
temp->next = h1;
h1 = temp;
cnt++;
t = t->next;
}
if (cnt < k) return;
tail->next = h1;
cnt = 0;
while (cnt < k) {
cnt++;
tail = tail->next;
}
tail->next = t;
}
};
fun(t, tail, k);
return root->next;
}
};