Reverse a Linked List in groups of given size using Stack
Last Updated : 12 Sep, 2024
Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should be considered as a group and must be reversed.
Examples:
Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL, k = 2 Output: head: 2 -> 1 -> 4 -> 3 -> 6 -> 5 -> NULL Explanation : Linked List is reversed in a group of size k = 2.
Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL, k = 4 Output: head: 4 -> 3 -> 2 -> 1 -> 6 -> 5 -> NULL Explanation : Linked List is reversed in a group of size k = 4.
Approach:
The idea is to use a Stack to store the nodes of the given linked list. Firstly, push the k nodes of the linked list into the stack. Now, pop the nodes one by one and keep track of the previously popped node. Point the next pointer of the prev node to the top element of the stack. Repeat this process, until we reach end of linked list.
Below is the implementation of the above approach:
C++
// C++ program to reverse a linked list in groups// of given size#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Function to reverse the linked list in groupsNode*reverseKGroup(Node*head,intk){if(!head||k==1){returnhead;}stack<Node*>st;Node*curr=head;Node*prev=nullptr;while(curr!=nullptr){// Terminate the loop when either// current == NULL or count >= k intcount=0;while(curr!=nullptr&&count<k){st.push(curr);curr=curr->next;count++;}// Now pop the elements from the stack one by one while(!st.empty()){// If the final list has not been started yetif(prev==nullptr){prev=st.top();head=prev;st.pop();}else{prev->next=st.top();prev=prev->next;st.pop();}}}// Set the next pointer of the // last node to NULLprev->next=nullptr;returnhead;}voidprintList(Node*head){Node*curr=head;while(curr!=nullptr){cout<<curr->data<<" ";curr=curr->next;}cout<<endl;}intmain(){// Creating a sample singly linked list:// 1 -> 2 -> 3 -> 4 -> 5 -> 6Node*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->next->next->next->next->next=newNode(6);head=reverseKGroup(head,3);printList(head);return0;}
Java
// Java program to reverse a linked list// in groups of given sizeimportjava.util.Stack;classNode{intdata;Nodenext;Node(intdata){this.data=data;this.next=null;}}// Function to reverse the linked list in groupsclassGfG{staticNodereverseKGroup(Nodehead,intk){if(head==null||k==1){returnhead;}Stack<Node>st=newStack<>();Nodecurr=head;Nodeprev=null;while(curr!=null){// Terminate the loop when either // current == null or count >= kintcount=0;while(curr!=null&&count<k){st.push(curr);curr=curr.next;count++;}// Now pop the elements from the stack one by onewhile(!st.isEmpty()){// If the final list has not been started yetif(prev==null){prev=st.pop();head=prev;}else{prev.next=st.pop();prev=prev.next;}}}// Set the next pointer of the last node to nullprev.next=null;returnhead;}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.data+" ");curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){// Creating a sample singly linked list:// 1 -> 2 -> 3 -> 4 -> 5 -> 6Nodehead=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.next.next.next.next.next=newNode(6);head=reverseKGroup(head,3);printList(head);}}
Python
# Python3 program to reverse a Linked List# in groups of given sizeclassNode:def__init__(self,data):self.data=dataself.next=None# Function to reverse the linked list in groupsdefreverseKGroup(head,k):ifnotheadork==1:returnheadst=[]curr=headprev=NonewhilecurrisnotNone:# Terminate the loop when either# current == None or count >= kcount=0whilecurrisnotNoneandcount<k:st.append(curr)curr=curr.nextcount+=1# Now pop the elements from the stack one by onewhilelen(st)>0:# If the final list has not been started yetifprevisNone:prev=st.pop()head=prevelse:prev.next=st.pop()prev=prev.next# Set the next pointer of the last node to Noneprev.next=NonereturnheaddefprintList(head):curr=headwhilecurrisnotNone:print(curr.data,end=" ")curr=curr.nextprint()if__name__=="__main__":# Creating a sample singly linked list:# 1 -> 2 -> 3 -> 4 -> 5 -> 6head=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.next.next.next.next.next=Node(6)head=reverseKGroup(head,3)printList(head)
C#
// C# program to reverse a linked list in // groups of given sizeusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodenext;publicNode(intdata){this.data=data;this.next=null;}}classGfG{// Function to reverse the linked list in groupsstaticNodereverseKGroup(Nodehead,intk){if(head==null||k==1){returnhead;}Stack<Node>st=newStack<Node>();Nodecurr=head;Nodeprev=null;while(curr!=null){// Terminate the loop when either// current == null or count >= kintcount=0;while(curr!=null&&count<k){st.Push(curr);curr=curr.next;count++;}// Now pop the elements from the // stack one by onewhile(st.Count>0){// If the final list has not been started yetif(prev==null){prev=st.Pop();head=prev;}else{prev.next=st.Pop();prev=prev.next;}}}// Set the next pointer of the last node to nullprev.next=null;returnhead;}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){Console.Write(curr.data+" ");curr=curr.next;}Console.WriteLine();}staticvoidMain(string[]args){// Creating a sample singly linked list:// 1 -> 2 -> 3 -> 4 -> 5 -> 6Nodehead=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.next.next.next.next.next=newNode(6);head=reverseKGroup(head,3);printList(head);}}
JavaScript
// JavaScript program to reverse a linked list// in groups of given sizeclassNode{constructor(data){this.data=data;this.next=null;}}// Function to reverse the linked list in groupsfunctionreverseKGroup(head,k){if(!head||k===1){returnhead;}letst=[];letcurr=head;letprev=null;while(curr!==null){// Terminate the loop when either // current == null or count >= kletcount=0;while(curr!==null&&count<k){st.push(curr);curr=curr.next;count++;}// Now pop the elements from the stack one by onewhile(st.length>0){// If the final list has not been started yetif(prev===null){prev=st.pop();head=prev;}else{prev.next=st.pop();prev=prev.next;}}}// Set the next pointer of the last node to nullprev.next=null;returnhead;}functionprintList(head){letcurr=head;while(curr!==null){console.log(curr.data+" ");curr=curr.next;}console.log();}// Creating a sample singly linked list:// 1 -> 2 -> 3 -> 4 -> 5 -> 6lethead=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.next.next.next.next.next=newNode(6);head=reverseKGroup(head,3);printList(head);
Output
3 2 1 6 5 4
Time Complexity: O(n), where n is the number of nodes in the linked list. Auxiliary Space: O(k)