Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Stack
  • Practice Stack
  • MCQs on Stack
  • Stack Tutorial
  • Stack Operations
  • Stack Implementations
  • Monotonic Stack
  • Infix to Postfix
  • Prefix to Postfix
  • Prefix to Infix
  • Advantages & Disadvantages
Open In App
Next Article:
Reverse given Linked List in groups of specific given sizes
Next article icon

Reverse a Linked List in groups of given size using Stack

Last Updated : 12 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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.

Reverse-a-Linked-List-in-groups-of-given-size-1


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.

Reverse-a-Linked-List-in-groups-of-given-size-2

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> using namespace std;  class Node {   public:     int data;     Node *next;      Node(int x) {         data = x;         next = nullptr;     } };  // Function to reverse the linked list in groups Node *reverseKGroup(Node *head, int k) {     if (!head || k == 1) {         return head;     }      stack<Node*> st;      Node *curr = head;      Node *prev = nullptr;         while (curr != nullptr) {             // Terminate the loop when either       	// current == NULL or count >= k          int count = 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 yet             if (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 NULL     prev->next = nullptr;         return head;  }  void printList(Node *head) {     Node *curr = head;     while (curr != nullptr) {         cout << curr->data << " ";         curr = curr->next;     }     cout << endl; }  int main() {          // Creating a sample singly linked list:     // 1 -> 2 -> 3 -> 4 -> 5 -> 6     Node *head = new Node(1);     head->next = new Node(2);     head->next->next = new Node(3);     head->next->next->next = new Node(4);     head->next->next->next->next = new Node(5);     head->next->next->next->next->next = new Node(6);      head = reverseKGroup(head, 3);          printList(head);      return 0; } 
Java
// Java program to reverse a linked list // in groups of given size  import java.util.Stack;  class Node {     int data;     Node next;      Node(int data) {         this.data = data;         this.next = null;     } }  // Function to reverse the linked list in groups class GfG {     static Node reverseKGroup(Node head, int k) {         if (head == null || k == 1) {             return head;         }          Stack<Node> st = new Stack<>();         Node curr = head;         Node prev = null;          while (curr != null) {              // Terminate the loop when either            	// current == null or count >= k             int count = 0;             while (curr != null && count < k) {                 st.push(curr);                 curr = curr.next;                 count++;             }              // Now pop the elements from the stack one by one             while (!st.isEmpty()) {                                // If the final list has not been started yet                 if (prev == null) {                     prev = st.pop();                     head = prev;                 } else {                     prev.next = st.pop();                     prev = prev.next;                 }             }         }          // Set the next pointer of the last node to null         prev.next = null;          return head;     }      static void printList(Node head) {         Node curr = head;         while (curr != null) {             System.out.print(curr.data + " ");             curr = curr.next;         }         System.out.println();     }      public static void main(String[] args) {                // Creating a sample singly linked list:         // 1 -> 2 -> 3 -> 4 -> 5 -> 6         Node head = new Node(1);         head.next = new Node(2);         head.next.next = new Node(3);         head.next.next.next = new Node(4);         head.next.next.next.next = new Node(5);         head.next.next.next.next.next = new Node(6);          head = reverseKGroup(head, 3);          printList(head);     } } 
Python
# Python3 program to reverse a Linked List # in groups of given size  class Node:     def __init__(self, data):         self.data = data         self.next = None  # Function to reverse the linked list in groups def reverseKGroup(head, k):     if not head or k == 1:         return head      st = []     curr = head     prev = None      while curr is not None:                # Terminate the loop when either         # current == None or count >= k         count = 0         while curr is not None and count < k:             st.append(curr)             curr = curr.next             count += 1          # Now pop the elements from the stack one by one         while len(st) > 0:                        # If the final list has not been started yet             if prev is None:                 prev = st.pop()                 head = prev             else:                 prev.next = st.pop()                 prev = prev.next      # Set the next pointer of the last node to None     prev.next = None      return head  def printList(head):     curr = head     while curr is not None:         print(curr.data, end=" ")         curr = curr.next     print()  if __name__ == "__main__":        # Creating a sample singly linked list:     # 1 -> 2 -> 3 -> 4 -> 5 -> 6     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.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 size  using System; using System.Collections.Generic;  class Node {     public int data;     public Node next;      public Node(int data) {         this.data = data;         this.next = null;     } }  class GfG {        // Function to reverse the linked list in groups     static Node reverseKGroup(Node head, int k) {         if (head == null || k == 1) {             return head;         }          Stack<Node> st = new Stack<Node>();         Node curr = head;         Node prev = null;          while (curr != null) {                        // Terminate the loop when either           	// current == null or count >= k             int count = 0;             while (curr != null && count < k) {                 st.Push(curr);                 curr = curr.next;                 count++;             }              // Now pop the elements from the            // stack one by one             while (st.Count > 0) {                                // If the final list has not been started yet                 if (prev == null) {                     prev = st.Pop();                     head = prev;                 } else {                     prev.next = st.Pop();                     prev = prev.next;                 }             }         }          // Set the next pointer of the last node to null         prev.next = null;          return head;     }      static void printList(Node head) {         Node curr = head;         while (curr != null) {             Console.Write(curr.data + " ");             curr = curr.next;         }         Console.WriteLine();     }      static void Main(string[] args) {                // Creating a sample singly linked list:         // 1 -> 2 -> 3 -> 4 -> 5 -> 6         Node head = new Node(1);         head.next = new Node(2);         head.next.next = new Node(3);         head.next.next.next = new Node(4);         head.next.next.next.next = new Node(5);         head.next.next.next.next.next = new Node(6);          head = reverseKGroup(head, 3);          printList(head);     } } 
JavaScript
// JavaScript program to reverse a linked list // in groups of given size  class Node {     constructor(data) {         this.data = data;         this.next = null;     } }  // Function to reverse the linked list in groups function reverseKGroup(head, k) {     if (!head || k === 1) {         return head;     }      let st = [];     let curr = head;     let prev = null;      while (curr !== null) {              // Terminate the loop when either          // current == null or count >= k         let count = 0;         while (curr !== null && count < k) {             st.push(curr);             curr = curr.next;             count++;         }          // Now pop the elements from the stack one by one         while (st.length > 0) {                      // If the final list has not been started yet             if (prev === null) {                 prev = st.pop();                 head = prev;             } else {                 prev.next = st.pop();                 prev = prev.next;             }         }     }      // Set the next pointer of the last node to null     prev.next = null;      return head; }  function printList(head) {     let curr = head;     while (curr !== null) {         console.log(curr.data + " ");         curr = curr.next;     }     console.log(); }  // Creating a sample singly linked list: // 1 -> 2 -> 3 -> 4 -> 5 -> 6 let head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); head.next.next.next.next.next = new Node(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)

Related articles:

  • Reverse a Linked List in groups of given size using Deque
  • Reverse a singly Linked List in groups of given size (Recursive Approach)
  • Reverse a singly Linked List in groups of given size (Iterative Approach)


Next Article
Reverse given Linked List in groups of specific given sizes
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Algorithms
  • DSA
  • Linked List
  • Stack
  • Accolite
  • Adobe
  • MakeMyTrip
  • Microsoft
  • Paytm
  • Snapdeal
  • VMWare
Practice Tags :
  • Accolite
  • Adobe
  • MakeMyTrip
  • Microsoft
  • Paytm
  • Snapdeal
  • VMWare
  • Algorithms
  • Linked List
  • Stack

Similar Reads

  • Reverse a Linked List in groups of given size using Deque
    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 -
    8 min read
  • Reverse a Linked List in groups of given size
    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. Example: Input: head: 1 -> 2 -> 3 -> 4 -> 5 ->
    3 min read
  • Reverse given Linked List in groups of specific given sizes
    Given the linked list and an array arr[] of size N, the task is to reverse every arr[i] nodes of the list at a time (0 ≤ i < N). Note: If the number of nodes in the list is greater than the sum of array, then the remaining nodes will remain as it is. Examples: Input: head = 1->2->3->4-
    8 min read
  • Reverse a doubly linked list in groups of given size | Set 2
    Given a doubly-linked list containing n nodes. The problem is to reverse every group of k nodes in the list. Examples: Input: List: 10<->8<->4<->2, K=2Output: 8<->10<->2<->4 Input: List: 1<->2<->3<->4<->5<->6<->7<->8, K=3O
    15+ min read
  • XOR Linked List - Reverse a Linked List in groups of given size
    Given a XOR linked list and an integer K, the task is to reverse every K nodes in the given XOR linked list. Examples: Input: XLL = 7< – > 6 < – > 8 < – > 11 < – > 3, K = 3 Output: 8 < – > 6 < – > 7 < – > 3 < – > 11 Explanation: Reversing first K(= 3)
    13 min read
  • Reverse a doubly linked list in groups of K size
    Given a Doubly 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: 1 <-> 2 <-> 3 <-> 4 <-
    15+ min read
  • Reverse a Linked List in groups of given size (Iterative Approach)
    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 -
    10 min read
  • Reverse a singly Linked List in groups of given size (Recursive Approach)
    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. Example: Input: head: 1 -> 2 -> 3 -> 4 -> 5 ->
    9 min read
  • Print Reverse a linked list using Stack
    Given a linked list, print the reverse of it without modifying the list. Examples: Input : 1 2 3 4 5 6 Output : 6 5 4 3 2 1 Input : 12 23 34 45 56 67 78 Output : 78 67 56 45 34 23 12 Below are different solutions that are now allowed here as we cannot use extra space and modify the list. Recursive s
    9 min read
  • Javascript Program For Reversing A Linked List In Groups Of Given Size- Set 2
    Given a linked list, write a function to reverse every k nodes (where k is an input to the function). Examples: Input: 1->2->3->4->5->6->7->8->NULL and k = 3 Output: 3->2->1->6->5->4->8->7->NULL. Input: 1->2->3->4->5->6->7->8->N
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences