Home » Technical Interview Questions » LinkedList Interview Questions » Reverse a Linked List in groups

# Reverse a Linked List in groups

## In the given linked list, write a function to reverse every set of k nodes. (K is input value)

### Example ## Algorithm

Time complexity : O(n)

a. Create a function ReverseInGroups to reverse the linked list in set of sub-lists of size k.

b. In this function, we use recursive method

1) First reverse the first sub-list of size of k.

2) Keep track of the next node(next) and previous nodes(previous).

3) Function returns previous, which becomes the head of the list.

4) For the rest of list call the recursive function and link the two sub-lists. ## C++ Program

```#include <bits/stdc++.h>

using namespace std;

struct LLNode
{
int data;
struct LLNode* next;
};

struct LLNode *reverse(struct LLNode *head, int k)
{
//Initialize next and previous as null
struct LLNode* next = NULL;
struct LLNode* previous = NULL;
int count = 0;

//reverse first k nodes
while (curr != NULL && count < k)
{
next  = curr->next;
curr->next = previous;
previous = curr;
curr = next;
count = count + 1;
}
if (next !=  NULL)
{
}

return previous;
}

/* Function to insertAtBeginning a node */
void insertAtBeginning(struct LLNode** head, int dataToBeInserted)
{
struct LLNode* curr = new LLNode;
curr->data = dataToBeInserted;
curr->next = NULL;
*head=curr; //if this is first node make this as head of list

else
{
curr->next=*head; //else make the curr (new) node's next point to head and make this new node a the head
}

//O(1) constant time
}

void display(struct LLNode**node)
{
struct LLNode *temp= *node;
while(temp!=NULL)
{
if(temp->next!=NULL)
cout<<temp->data<<" ->";
else
cout<<temp->data;

temp=temp->next; //move to next node
}
//O(number of nodes)
cout<<endl;
}
//Main function
int main(void)
{

struct LLNode* head = NULL;//initial list has no elements

cout<<"The list initially is :-\n";