Reverse a Linked List in groups of given size | Set 2

24 Jun, 2022
Given a linked list, write a function to reverse every k node (where k is an input to the function). Examples:  
Inputs:  1->2->3->4->5->6->7->8->NULL and k = 3 
Output:  3->2->1->6->5->4->8->7->NULL. 

Inputs:   1->2->3->4->5->6->7->8->NULL and k = 5
Output:  5->4->3->2->1->8->7->6->NULL.
 
We have already discussed its solution in the below post Reverse a Linked List in groups of given size | Set 1In this post, we have used a stack that will store the nodes of the given linked list. Firstly, push the k elements of the linked list in the stack. Now pop elements 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 NULL is reached.This algorithm uses O(k) extra space.  
C++
Java
Python3
C#
Javascript
// C++ program to reverse a linked list in groups// of given size#include <bits/stdc++.h>using namespace std;  /* Link list node */struct Node {    int data;    struct Node* next;};  /* Reverses the linked list in groups of size k   and returns the pointer to the new head node. */struct Node* Reverse(struct Node* head, int k){    // Create a stack of Node*    stack<Node*> mystack;    struct Node* current = head;    struct Node* prev = NULL;      while (current != NULL) {          // Terminate the loop whichever comes first        // either current == NULL or count >= k        int count = 0;        while (current != NULL && count < k) {            mystack.push(current);            current = current->next;            count++;        }          // Now pop the elements of stack one by one        while (mystack.size() > 0) {              // If final list has not been started yet.            if (prev == NULL) {                prev = mystack.top();                head = prev;                mystack.pop();            } else {                prev->next = mystack.top();                prev = prev->next;                mystack.pop();            }        }    }      // Next of last element will point to NULL.    prev->next = NULL;      return head;}  /* UTILITY FUNCTIONS *//* Function to push a node */void push(struct Node** head_ref, int new_data){    /* allocate node */    struct Node* new_node =           (struct Node*)malloc(sizeof(struct Node));      /* put in the data  */    new_node->data = new_data;      /* link the old list off the new node */    new_node->next = (*head_ref);      /* move the head to point to the new node */    (*head_ref) = new_node;}  /* Function to print linked list */void printList(struct Node* node){    while (node != NULL) {        printf("%d  ", node->data);        node = node->next;    }}  /* Driver program to test above function*/int main(void){    /* Start with the empty list */    struct Node* head = NULL;      /* Created Linked list is 1->2->3->4->5->6->7->8->9 */    push(&head, 9);    push(&head, 8);    push(&head, 7);    push(&head, 6);    push(&head, 5);    push(&head, 4);    push(&head, 3);    push(&head, 2);    push(&head, 1);      printf("\nGiven linked list \n");    printList(head);    head = Reverse(head, 3);      printf("\nReversed Linked list \n");    printList(head);      return 0;}
// Java program to reverse a linked list in groups // of given size import java.util.*;class GfG {      /* Link list node */static class Node {     int data;     Node next; }static Node head = null;  /* Reverses the linked list in groups of size k and returns the pointer to the new head node. */static Node Reverse(Node head, int k) {     // Create a stack of Node*     Stack<Node> mystack = new Stack<Node> ();     Node current = head;     Node prev = null;       while (current != null)    {           // Terminate the loop whichever comes first         // either current == NULL or count >= k         int count = 0;         while (current != null && count < k)        {             mystack.push(current);             current = current.next;             count++;         }           // Now pop the elements of stack one by one         while (mystack.size() > 0)         {               // If final list has not been started yet.             if (prev == null)            {                 prev = mystack.peek();                 head = prev;                 mystack.pop();             }             else            {                 prev.next = mystack.peek();                 prev = prev.next;                 mystack.pop();             }         }     }       // Next of last element will point to NULL.     prev.next = null;       return head; }   /* UTILITY FUNCTIONS *//* Function to push a node */static void push( int new_data) {     /* allocate node */    Node new_node = new Node();       /* put in the data */    new_node.data = new_data;       /* link the old list off the new node */    new_node.next = head;       /* move the head to point to the new node */    head = new_node; }   /* Function to print linked list */static void printList(Node node) {     while (node != null)     {         System.out.print(node.data + " ");         node = node.next;     } }   /* Driver code*/public static void main(String[] args) {     /* Start with the empty list */    //Node head = null;       /* Created Linked list is 1->2->3->    4->5->6->7->8->9 */    push( 9);     push( 8);     push( 7);     push( 6);     push( 5);     push(4);     push(3);     push(2);     push( 1);       System.out.println("Given linked list ");     printList(head);     head = Reverse(head, 3);    System.out.println();      System.out.println("Reversed Linked list ");     printList(head); } }   // This code is contributed by Prerna Saini
# Python3 program to reverse a Linked List# in groups of given size  # Node classclass Node(object):    __slots__ = 'data', 'next'      # Constructor to initialize the node object    def __init__(self, data = None, next = None):        self.data = data        self.next = next      def __repr__(self):        return repr(self.data)  class LinkedList(object):      # Function to initialize head    def __init__(self):        self.head = None      # Utility function to print nodes     # of LinkedList    def __repr__(self):        nodes = []        curr = self.head        while curr:            nodes.append(repr(curr))            curr = curr.next        return '[' + ', '.join(nodes) + ']'      # Function to insert a new node at    # the beginning    def prepend(self, data):        self.head = Node(data = data,                         next = self.head)      # Reverses the linked list in groups of size k    # and returns the pointer to the new head node.    def reverse(self, k = 1):        if self.head is None:            return          curr = self.head        prev = None        new_stack = []        while curr is not None:            val = 0                          # Terminate the loop whichever comes first            # either current == None or value >= k            while curr is not None and val < k:                new_stack.append(curr.data)                curr = curr.next                val += 1              # Now pop the elements of stack one by one            while new_stack:                                  # If final list has not been started yet.                if prev is None:                    prev = Node(new_stack.pop())                    self.head = prev                else:                    prev.next = Node(new_stack.pop())                    prev = prev.next                              # Next of last element will point to None.        prev.next = None        return self.head  # Driver Codellist = LinkedList() llist.prepend(9)llist.prepend(8)llist.prepend(7)llist.prepend(6)llist.prepend(5)llist.prepend(4)llist.prepend(3)llist.prepend(2)llist.prepend(1)  print("Given linked list")print(llist)llist.head = llist.reverse(3)  print("Reversed Linked list")print(llist)  # This code is contributed by # Sagar Kumar Sinha(sagarsinha7777)
// C# program to reverse a linked list  // in groups of given size using System;using System.Collections;  class GfG {       /* Link list node */public class Node {     public int data;     public Node next; } static Node head = null;   /* Reverses the linked list in groups of size k and returns the pointer to the new head node. */static Node Reverse(Node head, int k) {     // Create a stack of Node*     Stack mystack = new Stack();     Node current = head;     Node prev = null;       while (current != null)     {           // Terminate the loop whichever comes first         // either current == NULL or count >= k         int count = 0;         while (current != null && count < k)         {             mystack.Push(current);             current = current.next;             count++;         }           // Now Pop the elements of stack one by one         while (mystack.Count > 0)         {               // If final list has not been started yet.             if (prev == null)             {                 prev = (Node)mystack.Peek();                 head = prev;                 mystack.Pop();             }             else            {                 prev.next = (Node)mystack.Peek();                 prev = prev.next;                 mystack.Pop();             }         }     }       // Next of last element will point to NULL.     prev.next = null;       return head; }   /* UTILITY FUNCTIONS *//* Function to Push a node */static void Push( int new_data) {     /* allocate node */    Node new_node = new Node();       /* put in the data */    new_node.data = new_data;       /* link the old list off the new node */    new_node.next = head;       /* move the head to point to the new node */    head = new_node; }   /* Function to print linked list */static void printList(Node node) {     while (node != null)     {         Console.Write(node.data + " ");         node = node.next;     } }   /* Driver code*/public static void Main(String []args) {     /* Start with the empty list */    //Node head = null;       /* Created Linked list is 1->2->3->     4->5->6->7->8->9 */    Push( 9);     Push( 8);     Push( 7);     Push( 6);     Push( 5);     Push(4);     Push(3);     Push(2);     Push( 1);       Console.WriteLine("Given linked list ");     printList(head);     head = Reverse(head, 3);     Console.WriteLine();       Console.WriteLine("Reversed Linked list ");     printList(head); } }   // This code is contributed by Arnab Kundu
<script>// javascript program to reverse a linked list in groups // of given size class GfG {      /* Link list node */class Node {    constructor() {        this.data = 0;        this.next = null;    }}      var head = null;      /*     * Reverses the linked list in groups of size k and returns the pointer to the     * new head node.     */    function Reverse(head , k) {        // Create a stack of Node*        var mystack = [];var current = head;var prev = null;          while (current != null) {              // Terminate the loop whichever comes first            // either current == NULL or count >= k            var count = 0;            while (current != null && count < k) {                mystack.push(current);                current = current.next;                count++;            }              // Now pop the elements of stack one by one            while (mystack.length > 0) {                  // If final list has not been started yet.                if (prev == null) {                    prev = mystack.pop();                    head = prev;                                      } else {                    prev.next = mystack.pop();                    prev = prev.next;                                      }            }        }          // Next of last element will point to NULL.        prev.next = null;          return head;    }      /* UTILITY FUNCTIONS */    /* Function to push a node */    function push(new_data) {        /* allocate node */var new_node = new Node();          /* put in the data */        new_node.data = new_data;          /* link the old list off the new node */        new_node.next = head;          /* move the head to point to the new node */        head = new_node;    }      /* Function to print linked list */    function printList(node) {        while (node != null) {            document.write(node.data + " ");            node = node.next;        }    }      /* Driver code */              /* Start with the empty list */        // Node head = null;          /*         * Created Linked list is 1->2->3-> 4->5->6->7->8->9         */        push(9);        push(8);        push(7);        push(6);        push(5);        push(4);        push(3);        push(2);        push(1);          document.write("Given linked list <br/>");        printList(head);        head = Reverse(head, 3);        document.write("<br/>");          document.write("Reversed Linked list <br/>");        printList(head);  // This code contributed by aashish1995 </script>
Output:  
Given Linked List
1 2 3 4 5 6 7 8 9 
Reversed list
3 2 1 6 5 4 9 8 7
Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the number of nodes in the linked list.
Auxiliary Space: O(k), as we are using extra space for the stack. 
Reverse a Linked List in groups of given size | Set 2 | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersReverse a Linked List in groups of given size | Set 2 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:06•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=aF9PGkR0dWU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. 
sagarsinha7777
prerna saini
andrew1234
nidhi_biet
aashish1995
arorakashish0911
rohan07
Accolite
Adobe
MakeMyTrip
Microsoft
Paytm
Snapdeal
VMWare
Linked List
Paytm
VMWare
Accolite
Microsoft
Snapdeal
MakeMyTrip
Adobe
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Implementing a Linked List in Java using Class
Find Length of a Linked List (Iterative and Recursive)
Queue - Linked List Implementation
Function to check if a singly linked list is palindrome
Remove duplicates from an unsorted linked list
Write a function to get the intersection point of two Linked Lists
Circular Linked List | Set 1 (Introduction and Applications)
Implement a stack using singly linked list