# Reverse a Doubly-Linked List in Groups of a Given Size using C++

In this problem, we are given a pointer to the head of a linked list and an integer k. In groups of size k, we need to reverse the linked list. For example −

Input : 1 <-> 2 <-> 3 <-> 4 <-> 5 (doubly linked list), k = 3
Output : 3 <-> 2 <-> 1 <-> 5 <-> 4

## Approach to find The Solution

In this problem, we are going to make a recursive algorithm to solve this problem. In this approach, we are going to use recursion and solve the problem using that.

## Example

#include <iostream>
using namespace std;
struct Node {
int data;
Node *next, *prev;
};
// push function to push a node into the list
Node* push(Node* head, int data) {
Node* new_node = new Node();
new_node->data = data;
new_node->next = NULL;
new_node->prev = NULL;
}
while (TMP->next != NULL) { // going to the last node
TMP = TMP->next;
}
TMP->next = new_node;
new_node->prev = TMP;
}
// function to print given list
cout << head->data << " ";
}
cout << endl;
}
Node* revK(Node* head, int k) {
return NULL;
int count = 0;
while (CURRENT != NULL && count < k) { // while our count is less than k we simply reverse                                                 the nodes.
TMP = CURRENT->prev;
CURRENT->prev = CURRENT->next;
CURRENT->next = TMP;
CURRENT = CURRENT->prev;
count++;
}
if (count >= k) {
head->next = revK(CURRENT, k); // now when if the count is greater or equal
}
}
int main() {
for (int i = 1; i <= 5; i++) {
}
cout << "Original List : ";
cout << "\nModified List : ";
int k = 3;
}



## Output

Original List : 1 2 3 4 5
Modified List : 3 2 1 5 4

## Explanation of the above code

In this approach, we are traversing through the list and traversing till our count is less than k. We make and recursive call give that value to head -> next( here we are simply reversing the list as we go through, but when our k is reached, we need to make our head point to another lists kth element for example, if our list is 1 2 3 4 5 and our k is 3 in this we reverse the middle elements to 3 2 1 but now we need our 1 to point to 4 as that element is also going to be reversed, so that is why we are using recursive calls and making an extra if statement.).

## Conclusion

In this article, we solve a problem to Reverse a doubly-linked list in groups of a given size using recursion. We also learned the C++ program for this problem and the complete approach we solved. We can write the same program in other languages such as C, java, python, and other languages. We hope you find this article helpful.