# Reverse Nodes in k-Group in C++

C++Server Side ProgrammingProgramming

Suppose we have a linked list, we have to reverse the nodes of the linked list k at a time and return its modified list. Here k is a positive integer and is less than or equal to the length of the linked list. So if the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.

So if the linked list is like [1,2,3,4,5,6,7] and k is 3, then the result will be [3,2,1,6,5,4,7].

To solve this, we will follow these steps −

• Define a method called solve(), this will take the head of the linked list, take partCount and k

• if partCount is 0, then return head

• while newHead is not null and x is not 0

• return prev

• From the main method do the following −

• return solve(head of the linked list, length of list / k, k)

## Example

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
void print_vector(vector<vector<auto>> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << "[";
for(int j = 0; j <v[i].size(); j++){
cout << v[i][j] << ", ";
}
cout << "],";
}
cout << "]"<<endl;
}
class ListNode{
public:
int val;
ListNode *next;
ListNode(int data){
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int> v){
for(int i = 1; i<v.size(); i++){
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
}
cout << "[";
while(ptr){
cout << ptr->val << ", ";
ptr = ptr->next;
}
cout << "]" << endl;
}
class Solution {
public:
ListNode* solve(ListNode* head, int partitionCount, int k){
ListNode* prev = NULL;
ListNode* temp;
int x = k;
}
return prev;
}
int len = 0;
while(curr){
len++;
curr = curr->next;
}
return len;
}
ListNode* reverseKGroup(ListNode* head, int k) {
return solve(head, length / k, k);
}
};
main(){
vector<int> v = {1,2,3,4,5,6,7};
Solution ob;
}
1,2,3,4,5,6,7
3
[3, 2, 1, 6, 5, 4, 7, ]