Reverse a Linked List in groups of given size using Stack (original) (raw)
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> 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 headdef 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);
`
**Time Complexity: O(n), where **n is the number of nodes in the linked list.
**Auxiliary Space: O(k)
**Related articles:

