# C Program to Reverse a linked list in groups of given size

## Reverse a linked list in groups of given size

C Program to Reverse a linked list in groups of given size. In this we will reverse the sub-nodes of the linked list according to the user given size, it is somehow same as reverse the nodes of the linked list which is not a big deal to reverse nodes of the linked list.
For Example:-
Input:- 31 -> 12 -> 4-> 24 -> 65 -> 76 ->7 -> 18; m = 2(given size by user)
Output:- 12 -> 31 -> 24 -> 4 -> 76 -> 65 -> 18 -> 7; reverse of nodes as per user group size is 2. ## Steps required for Reverse a linked list in groups of given size:-

• First of all we have to reverse the first sub nodes of the size m according to the user requirement.
• While reversing the linked list keep observe the next node and previous node.
• Now lets take the pointer to the next node be next and pointer to the previous node be prev.
• Then take as head -> next = reverse (next, m).
• Return prev. ## Structure for creating node in the singly linked list:-

`struct node{int data;struct node *next;};`

## C Program to Reverse a linked list in groups of given size

```#include <stdio.h>
#include  <stdlib.h>
struct Node         // Structure of node
{
int item;
struct Node* next;
};
struct Node *reverse (struct Node *head, int m) /* this function reverses the linked list in groups of size m and
returns the pointer to the new head node*/
{
struct Node* next = NULL;
struct Node* previous = NULL;

void print_List(struct Node *node) //print function of the list
{
while (node != NULL)
{
printf("%d ",node->item);
node = node->next;
}
}
void insert(struct Node** head_ref, int new_data) //insert the data
{
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
new_Node->item = new_Data;
}
int counter = 0;
while (current != NULL && counter < m) //reverse first m nodes of the linked list
{
next = current->next;
current->next = previous;
previous = current;
current = next;
counter++;
}

if (next != NULL)
return previous;
}

int main()
{
```Output:-