Givenhead of linked list and an integer k, reverse the list in groups of size k. If the total number of nodes is not a multiple of k, the remaining nodes at the end should also be treated as a group and reversed.
Examples:
Input: k = 2
Output: 2 -> 1 -> 4 -> 3 -> 6 -> 5 -> NULL Explanation: Linked List is reversed in a group of size k = 2.
Input: k = 4
Output: 4 -> 3 -> 2 -> 1 -> 6 -> 5 -> NULL Explanation: Linked List is reversed in a group of size k = 4.
Iterative K-Group Reversal - O(n) Time and O(1) Space
To reverse a linked list in groups of size k, the goal is to traverse the list in segments of k nodes and reverse each group individually. After reversing each group, we connect it to the previous group by updating the tail pointer. This will continues until the entire list is traversed, and we return the new head of the reversed list.
Initialize curr to the head and maintain newHead and tail to connect the reversed groups.
Process the linked list group by group, taking at most k nodes at a time.
Reverse the current group using three pointers: prev, curr, and nextNode.
For the first group, set newHead = prev, as prev becomes the new head of the list.
Connect the previous group's tail to prev, then update tail to the original group's head.
Continue until all nodes are processed and return newHead.
Illustrations:
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};Node*reverseKGroup(Node*head,intk){if(head==nullptr){returnhead;}Node*curr=head;Node*newHead=nullptr;Node*tail=nullptr;while(curr!=nullptr){Node*groupHead=curr;Node*prev=nullptr;Node*nextNode=nullptr;intcount=0;// Reverse the nodes in the current groupwhile(curr!=nullptr&&count<k){nextNode=curr->next;curr->next=prev;prev=curr;curr=nextNode;count++;}// If newHead is null, set it to the// last node of the first groupif(newHead==nullptr){newHead=prev;}// Connect the previous group to the // current reversed groupif(tail!=nullptr){tail->next=prev;}// Move tail to the end of the reversed grouptail=groupHead;}returnnewHead;}voidprintList(Node*head){Node*curr=head;while(curr!=nullptr){cout<<curr->data;if(curr->next!=NULL){cout<<" -> ";}curr=curr->next;}cout<<endl;}intmain(){Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->next->next->next=newNode(4);head->next->next->next->next=newNode(5);head=reverseKGroup(head,3);printList(head);return0;}
C
#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};structNode*reverseKGroup(structNode*head,intk){if(head==NULL){returnhead;}structNode*curr=head;structNode*newHead=NULL;structNode*tail=NULL;while(curr!=NULL){structNode*groupHead=curr;structNode*prev=NULL;structNode*nextNode=NULL;intcount=0;// Reverse the nodes in the current groupwhile(curr!=NULL&&count<k){nextNode=curr->next;curr->next=prev;prev=curr;curr=nextNode;count++;}// If newHead is null, set it to the// last node of the first groupif(newHead==NULL){newHead=prev;}// Connect the previous group to the // current reversed groupif(tail!=NULL){tail->next=prev;}// Move tail to the end of the // reversed grouptail=groupHead;}returnnewHead;}voidprintList(structNode*head){structNode*curr=head;while(curr!=NULL){printf("%d",curr->data);if(curr->next!=NULL){printf(" -> ");}curr=curr->next;}printf("\n");}structNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=x;newNode->next=NULL;returnnewNode;}intmain(){structNode*head=createNode(1);head->next=createNode(2);head->next->next=createNode(3);head->next->next->next=createNode(4);head->next->next->next->next=createNode(5);head=reverseKGroup(head,3);printList(head);return0;}
Java
classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{staticNodereverseKGroup(Nodehead,intk){if(head==null){returnhead;}Nodecurr=head;NodenewHead=null;Nodetail=null;while(curr!=null){NodegroupHead=curr;Nodeprev=null;NodenextNode=null;intcount=0;// Reverse the nodes in the current groupwhile(curr!=null&&count<k){nextNode=curr.next;curr.next=prev;prev=curr;curr=nextNode;count++;}// If newHead is null, set it to the// last node of the first groupif(newHead==null){newHead=prev;}// Connect the previous group to the // current reversed groupif(tail!=null){tail.next=prev;}// Move tail to the end of the// reversed grouptail=groupHead;}returnnewHead;}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.data);if(curr.next!=null){System.out.print(" -> ");}curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head=reverseKGroup(head,3);printList(head);}}
Python
classNode:def__init__(self,data):self.data=dataself.next=NonedefreverseKGroup(head,k):ifheadisNone:returnheadcurr=headnewHead=Nonetail=NonewhilecurrisnotNone:groupHead=currprev=NonenextNode=Nonecount=0# Reverse the nodes in the current groupwhilecurrisnotNoneandcount<k:nextNode=curr.nextcurr.next=prevprev=currcurr=nextNodecount+=1# If newHead is null, set it to the# last node of the first groupifnewHeadisNone:newHead=prev# Connect the previous group to the# current reversed groupiftailisnotNone:tail.next=prev# Move tail to the end of # the reversed grouptail=groupHeadreturnnewHeaddefprintList(head):curr=headwhilecurrisnotNone:print(curr.data,end="")ifcurr.next!=None:print(" -> ",end="");curr=curr.nextprint()if__name__=="__main__":head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(4)head.next.next.next.next=Node(5)head=reverseKGroup(head,3)printList(head)
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{staticNodereverseKGroup(Nodehead,intk){if(head==null){returnhead;}Nodecurr=head;NodenewHead=null;Nodetail=null;while(curr!=null){NodegroupHead=curr;Nodeprev=null;NodenextNode=null;intcount=0;// Reverse the nodes in the current groupwhile(curr!=null&&count<k){nextNode=curr.next;curr.next=prev;prev=curr;curr=nextNode;count++;}// If newHead is null, set it to the// last node of the first groupif(newHead==null){newHead=prev;}// Connect the previous group to the // current reversed groupif(tail!=null){tail.next=prev;}// Move tail to the end of the // reversed grouptail=groupHead;}returnnewHead;}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){Console.Write(curr.data);if(curr.next!=null){Console.Write(" -> ");}curr=curr.next;}Console.WriteLine();}staticvoidMain(string[]args){Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head=reverseKGroup(head,3);printList(head);}}
JavaScript
classNode{constructor(data){this.data=data;this.next=null;}}functionreverseKGroup(head,k){if(head===null){returnhead;}letcurr=head;letnewHead=null;lettail=null;while(curr!==null){letgroupHead=curr;letprev=null;letnextNode=null;letcount=0;// Reverse the nodes in the current groupwhile(curr!==null&&count<k){nextNode=curr.next;curr.next=prev;prev=curr;curr=nextNode;count++;}// If newHead is null, set it to the// last node of the first groupif(newHead===null){newHead=prev;}// Connect the previous group to the // current reversed groupif(tail!==null){tail.next=prev;}// Move tail to the end of the // reversed grouptail=groupHead;}returnnewHead;}functionprintList(head){letcurr=head;constout=[];while(curr!==null){out.push(curr.data.toString());curr=curr.next;}console.log(out.join(" -> "));}// Driver Codelethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head=reverseKGroup(head,3);printList(head);
Output
3 -> 2 -> 1 -> 5 -> 4
Recursive K-Group Reversal - O(n) Time and O(n/k) Space
The idea is to reverse the first k nodes of the list and update the head of the list to the new head of this reversed segment. Then, connect the tail of this reversed segment to the result of recursively reversing the remaining portion of the list.
If the list is empty, return head.
Traverse the next k nodes using temp to find the starting node of the next group.
Reverse the current k nodes using reverseKNodes(), which reverses the links one by one.
The original head becomes the tail of the reversed group, so connect it to the result of recursively processing the remaining list.
Recursively call reverseKGroup(temp, k) for the next group.
Return the new head (groupHead) of the reversed list.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Helper function to reverse K nodesNode*reverseKNodes(Node*head,intk){Node*curr=head,*prev=nullptr,*next=nullptr;intcount=0;while(curr!=nullptr&&count<k){next=curr->next;curr->next=prev;prev=curr;curr=next;count++;}returnprev;}// Recursive function to reverse in groups of KNode*reverseKGroup(Node*head,intk){if(head==nullptr){returnhead;}Node*groupHead=nullptr;Node*newHead=nullptr;// Move temp to the next groupNode*temp=head;intcount=0;while(temp&&count<k){temp=temp->next;count++;}// Reverse the first K nodesgroupHead=reverseKNodes(head,k);// Connect the reversed group with the next partif(newHead==nullptr){newHead=groupHead;}// Recursion for the next grouphead->next=reverseKGroup(temp,k);returnnewHead;}voidprintList(Node*head){Node*curr=head;while(curr!=nullptr){cout<<curr->data;if(curr->next!=NULL){cout<<" -> ";}curr=curr->next;}cout<<endl;}intmain(){// Creating a sample singly linked list:// 1 -> 2 -> 3 -> 4 -> 5Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->next->next->next=newNode(4);head->next->next->next->next=newNode(5);head=reverseKGroup(head,3);printList(head);return0;}
C
#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};// Helper function to reverse K nodesstructNode*reverseKNodes(structNode*head,intk){structNode*curr=head;structNode*prev=NULL;structNode*next=NULL;intcount=0;while(curr!=NULL&&count<k){next=curr->next;curr->next=prev;prev=curr;curr=next;count++;}returnprev;}// Recursive function to reverse in groups of KstructNode*reverseKGroup(structNode*head,intk){if(head==NULL){returnhead;}structNode*temp=head;intcount=0;while(temp!=NULL&&count<k){temp=temp->next;count++;}structNode*groupHead=reverseKNodes(head,k);// Recursion for the next grouphead->next=reverseKGroup(temp,k);returngroupHead;}voidprintList(structNode*head){structNode*curr=head;while(curr!=NULL){printf("%d",curr->data);if(curr->next!=NULL){printf(" -> ");}curr=curr->next;}printf("\n");}structNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=x;newNode->next=NULL;returnnewNode;}intmain(){// Creating a sample singly linked list:// 1 -> 2 -> 3 -> 4 -> 5structNode*head=createNode(1);head->next=createNode(2);head->next->next=createNode(3);head->next->next->next=createNode(4);head->next->next->next->next=createNode(5);head=reverseKGroup(head,3);printList(head);return0;}
Java
classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}// Helper function to reverse K nodesclassGfG{staticNodereverseKNodes(Nodehead,intk){Nodecurr=head;Nodeprev=null;Nodenext=null;intcount=0;while(curr!=null&&count<k){next=curr.next;curr.next=prev;prev=curr;curr=next;count++;}returnprev;}// Recursive function to reverse in groups of KstaticNodereverseKGroup(Nodehead,intk){if(head==null){returnhead;}Nodetemp=head;intcount=0;while(temp!=null&&count<k){temp=temp.next;count++;}NodegroupHead=reverseKNodes(head,k);// Recursion for the next grouphead.next=reverseKGroup(temp,k);returngroupHead;}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.data);if(curr.next!=null){System.out.print(" -> ");}curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){// Creating a sample singly linked list:// 1 -> 2 -> 3 -> 4 -> 5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head=reverseKGroup(head,3);printList(head);}}
Python
classNode:def__init__(self,x):self.data=xself.next=None# Helper function to reverse K nodesdefreverseKNodes(head,k):curr=headprev=Nonenext=Nonecount=0whilecurrisnotNoneandcount<k:next=curr.nextcurr.next=prevprev=currcurr=nextcount+=1returnprev# Recursive function to reverse in groups of KdefreverseKGroup(head,k):ifheadisNone:returnheadtemp=headcount=0whiletempisnotNoneandcount<k:temp=temp.nextcount+=1groupHead=reverseKNodes(head,k)# Recursion for the next grouphead.next=reverseKGroup(temp,k)returngroupHeaddefprintList(head):curr=headwhilecurrisnotNone:print(curr.data,end="")ifcurr.next!=None:print(" -> ",end="");curr=curr.nextprint()# Driver Codeif__name__=="__main__":# Creating a sample singly linked list:# 1 -> 2 -> 3 -> 4 -> 5head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(4)head.next.next.next.next=Node(5)head=reverseKGroup(head,3)printList(head)
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{// Helper function to reverse K nodesstaticNodereverseKNodes(Nodehead,intk){Nodecurr=head;Nodeprev=null;Nodenext=null;intcount=0;while(curr!=null&&count<k){next=curr.next;curr.next=prev;prev=curr;curr=next;count++;}returnprev;}// Recursive function to reverse in groups of KstaticNodereverseKGroup(Nodehead,intk){if(head==null){returnhead;}Nodetemp=head;intcount=0;while(temp!=null&&count<k){temp=temp.next;count++;}NodegroupHead=reverseKNodes(head,k);// Recursion for the next grouphead.next=reverseKGroup(temp,k);returngroupHead;}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){Console.Write(curr.data);if(curr.next!=null){Console.Write(" -> ");}curr=curr.next;}Console.WriteLine();}staticvoidMain(string[]args){// Creating a sample singly linked list:// 1 -> 2 -> 3 -> 4 -> 5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head=reverseKGroup(head,3);printList(head);}}
JavaScript
classNode{constructor(x){this.data=x;this.next=null;}}// Helper function to reverse K nodesfunctionreverseKNodes(head,k){letcurr=head;letprev=null;letnext=null;letcount=0;while(curr!==null&&count<k){next=curr.next;curr.next=prev;prev=curr;curr=next;count++;}returnprev;}// Recursive function to reverse in groups of KfunctionreverseKGroup(head,k){if(head===null){returnhead;}lettemp=head;letcount=0;while(temp!==null&&count<k){temp=temp.next;count++;}letgroupHead=reverseKNodes(head,k);// Recursion for the next grouphead.next=reverseKGroup(temp,k);returngroupHead;}functionprintList(head){letcurr=head;constout=[];while(curr!==null){out.push(curr.data.toString());curr=curr.next;}console.log(out.join(" -> "));}// Driver Codelethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head=reverseKGroup(head,3);printList(head);