Open In App

Reverse a Stack using Queue

Last Updated : 22 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.


Output

After 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:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads