Reverse a Stack using Queue
Last Updated :
22 Dec, 2022
Given a stack, the task is to reverse the stack using the queue data structure.
Examples:
Input: Stack: (Top to Bottom) [10 -> 20 -> 30 -> 40]
Output: Stack: (Top to Bottom) [40 -> 30 -> 20 -> 10]
Input: Stack: [6 -> 5 -> 4]
Output: Stack: [4 -> 5 -> 6]
Approach: The problem can be solved based on the following idea:
The stack follows LIFO order and the queue follows FIFO order. So, if we push all stack elements into queue and then push it back into the stack it will be reversed.
Illustration:
Consider Stack: [40 -> 30 -> 20 -> 10]
Step 1:
- Stack: (Bottom to Top) [40 -> 30 -> 20 -> 10]
Queue: (Front to Rear) Empty
Step 2:
- Stack: (Bottom to Top) [40 -> 30 -> 20]
Queue: (Front to Rear) 10
Step 3:
- Stack: (Bottom to Top) [40 -> 30]
Queue: (Front to Rear) [10 -> 20]
Step 4:
- Stack: (Bottom to Top) [40]
Queue: (Front to Rear) [10 -> 20 -> 30]
Step 5:
- Stack: (Bottom to Top) Empty
Queue: (Front to Rear) [10 -> 20 -> 30 -> 40]
Step 6:
- Stack: (Bottom to Top) [10]
Queue: (Front to Rear) [20 -> 30 -> 40]
Step 7:
- Stack: (Bottom to Top) [10 -> 20]
Queue: (Front to Rear) [30 -> 40]
Step 8:
- Stack: (Bottom to Top) [10 -> 20 -> 30]
Queue: (Front to Rear) [40]
Step 9:
- Stack: (Bottom to Top) [10 -> 20 -> 30 -> 40]
Queue: (Front to Rear) Empty
Follow the steps to solve the problem:
- Pop Elements one by one from the stack.
- Enqueue every popped element into the queue.
- Do it till the stack is empty.
- Then, Dequeue elements one by one from the queue.
- Push every dequeued element into the stack.
- Do it till the queue is empty.
- The stack is now reversed.
Below is the implementation for the above approach:
C++
// C++ code to reverse a stack using queue
#include <bits/stdc++.h>
using namespace std;
void reverse(stack<int>& stk)
{
queue<int> qu;
// Enqueue all into queue
while (!stk.empty()) {
qu.push(stk.top());
stk.pop();
}
// Now stack is empty thus push all
// elements back into the
// stack - FIFO order
while (!qu.empty()) {
stk.push(qu.front());
qu.pop();
}
}
// Driver Code
int main()
{
stack<int> stk;
stk.push(40);
stk.push(30);
stk.push(20);
stk.push(10);
// Function Call
reverse(stk);
// 40 30 20 10 (top to bottom)
cout << "After Reverse : (Top to Bottom)"
<< "\n";
while (!stk.empty()) {
cout << stk.top() << " ";
stk.pop();
}
cout << "\n";
return 0;
}
Java
// Java code to reverse a stack using queue
import java.io.*;
import java.util.*;
class GFG {
static void reverse(Stack<Integer> stk)
{
Queue<Integer> qu = new LinkedList<>();
// Enqueue all into queue
while (!stk.isEmpty()) {
qu.add(stk.peek());
stk.pop();
}
// Now stack is empty thus push all elements back
// into the stack - FIFO order
while (!qu.isEmpty()) {
stk.push(qu.peek());
qu.poll();
}
}
public static void main(String[] args)
{
Stack<Integer> stk = new Stack<>();
stk.push(40);
stk.push(30);
stk.push(20);
stk.push(10);
// Function call
reverse(stk);
// 40 30 20 10 (top to bottom)
System.out.println(
"After Reverse : (Top to Bottom)");
while (!stk.isEmpty()) {
System.out.print(stk.peek() + " ");
stk.pop();
}
System.out.println();
}
}
// This code is contributed by lokeshmvs21.
Python3
# Python code to reverse a stack using queue
from collections import deque
def reverse(stack):
queue = deque()
# Enqueue all into queue
while stack != []:
queue.append(stack.pop())
# Now stack is empty thus append all
# elements back into the
# stack - FIFO order
while queue:
stack.append(queue.popleft())
return stack
stack = []
stack.append(40)
stack.append(30)
stack.append(20)
stack.append(10)
# Function Call
stack = reverse(stack)
# 40 30 20 10 (top to bottom)
print("After Reverse : (Top to Bottom)")
while stack != []:
print(stack[-1], end=" ")
stack.pop()
# This code is contributed by hardikkhuswaha.
C#
// C# code to reverse a stack using queue
using System;
using System.Collections.Generic;
public class GFG {
static void Reverse(Stack<int> stk)
{
Queue<int> qu = new Queue<int>();
// Enqueue all into queue
while (stk.Count > 0) {
qu.Enqueue(stk.Peek());
stk.Pop();
}
// Now stack is empty thus push all elements back
// into the stack - FIFO order
while (qu.Count > 0) {
stk.Push(qu.Peek());
qu.Dequeue();
}
}
static public void Main()
{
// Code
Stack<int> stk = new Stack<int>();
stk.Push(40);
stk.Push(30);
stk.Push(20);
stk.Push(10);
// Function call
Reverse(stk);
// 40 30 20 10 (top to bottom)
Console.WriteLine(
"After Reverse : (Top to Bottom)");
while (stk.Count > 0) {
Console.Write(stk.Peek() + " ");
stk.Pop();
}
Console.WriteLine();
}
}
// This code is contributed by lokesh.
JavaScript
function reverse(stk) {
let qu = [];
// Enqueue all into queue
while (stk.length > 0) {
qu.push(stk.pop());
}
// Now stack is empty, so push all
// elements back into the stack
// in FIFO order
while (qu.length > 0) {
stk.push(qu.shift());
}
}
// Test the function
let stk = [10, 20, 30, 40];
// Function Call
reverse(stk);
// 40 30 20 10 (top to bottom)
console.log("After Reverse : (Top to Bottom)");
while (stk.length > 0) {
console.log(stk.pop() + " ");
}
// This code is contributed by aadityamaharshi21.
OutputAfter Reverse : (Top to Bottom)
40 30 20 10
Time Complexity: O(N), As we are popping out N elements, then only pushing N elements. N+N operations.
Auxiliary Space: O(N), As we are using an Extra Queue of N Space.
Related articles:
Similar Reads
Reverse an array using Stack Given an array arr[] of size n, the task is to reverse the array using Stack.Examples:Input: arr = [10, 20, 30, 40, 50] Output: 50 40 30 20 10 Explanation: Upon reversing the array becomes [50, 40, 30, 20, 10]. Therefore, the output is 50 40 30 20 10.Input: arr = [ 1 ]Output: 1Explanation: Reversing
4 min read
Reversing a Queue You are given a queue Q, and your task is to reverse the elements of the queue. You are only allowed to use the following standard queue operations:enqueue(x): Add an item x to the rear of the queue.dequeue(): Remove an item from the front of the queue.empty(): Check if the queue is empty or not.Exa
4 min read
Queue using Stacks Given a stack that supports push and pop operations, your task is to implement a queue using one or more instances of that stack along with its operations.Table of ContentBy Making Enqueue Operation CostlyBy Making Dequeue Operation Costly Queue Implementation Using One Stack and RecursionBy Making
11 min read
Reverse a String using Stack Given a string str, the task is to reverse it using stack. Example:Input: s = "GeeksQuiz"Output: ziuQskeeGInput: s = "abc"Output: cbaAlso read: Reverse a String â Complete Tutorial.As we all know, stacks work on the principle of first in, last out. After popping all the elements and placing them bac
3 min read
How to Reverse a Stack using Recursion Write a program to reverse a stack using recursion, without using any loop.Example: Input: elements present in stack from top to bottom 4 3 2 1Output: 1 2 3 4Input: elements present in stack from top to bottom 1 2 3Output: 3 2 1The idea of the solution is to hold all values in Function Call Stack un
4 min read