Implement Stack using Queues
The problem is opposite of this post. We are given a Queue data structure that supports standard operations like enqueue() and dequeue(). We need to implement a Stack data structure using only instances of Queue and queue operations allowed on the instances.
A stack can be implemented using two queues. Let stack to be implemented be ‘s’ and queues used to implement be ‘q1’ and ‘q2’. Stack ‘s’ can be implemented in two ways:
Method 1 (By making push operation costly)
This method makes sure that newly entered element is always at the front of ‘q1’, so that pop operation just dequeues from ‘q1’. ‘q2’ is used to put every new element at front of ‘q1’.
- push(s, x) operation’s step are described below:
- Enqueue x to q2
- One by one dequeue everything from q1 and enqueue to q2.
- Swap the names of q1 and q2
- pop(s) operation’s function are described below:
- Dequeue an item from q1 and return it.
Below is the implementation of the above approach:
C++
/* Program to implement a stack using two queue */ #include <bits/stdc++.h> using namespace std; class Stack { // Two inbuilt queues queue< int > q1, q2; // To maintain current number of // elements int curr_size; public : Stack() { curr_size = 0; } void push( int x) { curr_size++; // Push x first in empty q2 q2.push(x); // Push all the remaining // elements in q1 to q2. while (!q1.empty()) { q2.push(q1.front()); q1.pop(); } // swap the names of two queues queue< int > q = q1; q1 = q2; q2 = q; } void pop() { // if no elements are there in q1 if (q1.empty()) return ; q1.pop(); curr_size--; } int top() { if (q1.empty()) return -1; return q1.front(); } int size() { return curr_size; } }; // Driver code int main() { Stack s; s.push(1); s.push(2); s.push(3); cout << "current size: " << s.size() << endl; cout << s.top() << endl; s.pop(); cout << s.top() << endl; s.pop(); cout << s.top() << endl; cout << "current size: " << s.size() << endl; return 0; } // This code is contributed by Chhavi |
Java
/* Java Program to implement a stack using two queue */ import java.util.*; class GfG { static class Stack { // Two inbuilt queues static Queue<Integer> q1 = new LinkedList<Integer>(); static Queue<Integer> q2 = new LinkedList<Integer>(); // To maintain current number of // elements static int curr_size; Stack() { curr_size = 0 ; } static void push( int x) { curr_size++; // Push x first in empty q2 q2.add(x); // Push all the remaining // elements in q1 to q2. while (!q1.isEmpty()) { q2.add(q1.peek()); q1.remove(); } // swap the names of two queues Queue<Integer> q = q1; q1 = q2; q2 = q; } static void pop() { // if no elements are there in q1 if (q1.isEmpty()) return ; q1.remove(); curr_size--; } static int top() { if (q1.isEmpty()) return - 1 ; return q1.peek(); } static int size() { return curr_size; } } // driver code public static void main(String[] args) { Stack s = new Stack(); s.push( 1 ); s.push( 2 ); s.push( 3 ); System.out.println( "current size: " + s.size()); System.out.println(s.top()); s.pop(); System.out.println(s.top()); s.pop(); System.out.println(s.top()); System.out.println( "current size: " + s.size()); } } // This code is contributed by Prerna |
Python3
# Program to implement a stack using # two queue from queue import Queue class Stack: def __init__( self ): # Two inbuilt queues self .q1 = Queue() self .q2 = Queue() # To maintain current number # of elements self .curr_size = 0 def push( self , x): self .curr_size + = 1 # Push x first in empty q2 self .q2.put(x) # Push all the remaining # elements in q1 to q2. while ( not self .q1.empty()): self .q2.put( self .q1.queue[ 0 ]) self .q1.get() # swap the names of two queues self .q = self .q1 self .q1 = self .q2 self .q2 = self .q def pop( self ): # if no elements are there in q1 if ( self .q1.empty()): return self .q1.get() self .curr_size - = 1 def top( self ): if ( self .q1.empty()): return - 1 return self .q1.queue[ 0 ] def size( self ): return self .curr_size # Driver Code if __name__ = = '__main__' : s = Stack() s.push( 1 ) s.push( 2 ) s.push( 3 ) print ( "current size: " , s.size()) print (s.top()) s.pop() print (s.top()) s.pop() print (s.top()) print ( "current size: " , s.size()) # This code is contributed by PranchalK |
C#
/* C# Program to implement a stack using two queue */ using System; using System.Collections; class GfG { public class Stack { // Two inbuilt queues public Queue q1 = new Queue(); public Queue q2 = new Queue(); // To maintain current number of // elements public int curr_size; public Stack() { curr_size = 0; } public void push( int x) { curr_size++; // Push x first in empty q2 q2.Enqueue(x); // Push all the remaining // elements in q1 to q2. while (q1.Count > 0) { q2.Enqueue(q1.Peek()); q1.Dequeue(); } // swap the names of two queues Queue q = q1; q1 = q2; q2 = q; } public void pop() { // if no elements are there in q1 if (q1.Count == 0) return ; q1.Dequeue(); curr_size--; } public int top() { if (q1.Count == 0) return -1; return ( int )q1.Peek(); } public int size() { return curr_size; } }; // Driver code public static void Main(String[] args) { Stack s = new Stack(); s.push(1); s.push(2); s.push(3); Console.WriteLine( "current size: " + s.size()); Console.WriteLine(s.top()); s.pop(); Console.WriteLine(s.top()); s.pop(); Console.WriteLine(s.top()); Console.WriteLine( "current size: " + s.size()); } } // This code is contributed by Arnab Kundu |
current size: 3 3 2 1 current size: 1
Method 2 (By making pop operation costly)
In push operation, the new element is always enqueued to q1. In pop() operation, if q2 is empty then all the elements except the last, are moved to q2. Finally the last element is dequeued from q1 and returned.
- push(s, x) operation:
- Enqueue x to q1 (assuming size of q1 is unlimited).
- pop(s) operation:
- One by one dequeue everything except the last element from q1 and enqueue to q2.
- Dequeue the last item of q1, the dequeued item is result, store it.
- Swap the names of q1 and q2
- Return the item stored in step 2.
C++
/* Program to implement a stack using two queue */ #include <bits/stdc++.h> using namespace std; class Stack { queue< int > q1, q2; int curr_size; public : Stack() { curr_size = 0; } void pop() { if (q1.empty()) return ; // Leave one element in q1 and // push others in q2. while (q1.size() != 1) { q2.push(q1.front()); q1.pop(); } // Pop the only left element // from q1 q1.pop(); curr_size--; // swap the names of two queues queue< int > q = q1; q1 = q2; q2 = q; } void push( int x) { q1.push(x); curr_size++; } int top() { if (q1.empty()) return -1; while (q1.size() != 1) { q2.push(q1.front()); q1.pop(); } // last pushed element int temp = q1.front(); // to empty the auxiliary queue after // last operation q1.pop(); // push last element to q2 q2.push(temp); // swap the two queues names queue< int > q = q1; q1 = q2; q2 = q; return temp; } int size() { return curr_size; } }; // Driver code int main() { Stack s; s.push(1); s.push(2); s.push(3); s.push(4); cout << "current size: " << s.size() << endl; cout << s.top() << endl; s.pop(); cout << s.top() << endl; s.pop(); cout << s.top() << endl; cout << "current size: " << s.size() << endl; return 0; } // This code is contributed by Chhavi |
Java
/* Java Program to implement a stack using two queue */ import java.util.*; class Stack { Queue<Integer> q1 = new LinkedList<>(), q2 = new LinkedList<>(); int curr_size; public Stack() { curr_size = 0 ; } void remove() { if (q1.isEmpty()) return ; // Leave one element in q1 and // push others in q2. while (q1.size() != 1 ) { q2.add(q1.peek()); q1.remove(); } // Pop the only left element // from q1 q1.remove(); curr_size--; // swap the names of two queues Queue<Integer> q = q1; q1 = q2; q2 = q; } void add( int x) { q1.add(x); curr_size++; } int top() { if (q1.isEmpty()) return - 1 ; while (q1.size() != 1 ) { q2.add(q1.peek()); q1.remove(); } // last pushed element int temp = q1.peek(); // to empty the auxiliary queue after // last operation q1.remove(); // push last element to q2 q2.add(temp); // swap the two queues names Queue<Integer> q = q1; q1 = q2; q2 = q; return temp; } int size() { return curr_size; } // Driver code public static void main(String[] args) { Stack s = new Stack(); s.add( 1 ); s.add( 2 ); s.add( 3 ); s.add( 4 ); System.out.println( "current size: " + s.size()); System.out.println(s.top()); s.remove(); System.out.println(s.top()); s.remove(); System.out.println(s.top()); System.out.println( "current size: " + s.size()); } } // This code is contributed by Princi Singh |
Python3
# Program to implement a stack using # two queue from queue import Queue class Stack: def __init__( self ): # Two inbuilt queues self .q1 = Queue() self .q2 = Queue() # To maintain current number # of elements self .curr_size = 0 def push( self , x): self .q1.put(x) self .curr_size + = 1 def pop( self ): # if no elements are there in q1 if ( self .q1.empty()): return # Leave one element in q1 and push others in q2 while ( self .q1.qsize() ! = 1 ): self .q2.put( self .q1.get()) # Pop the only left element from q1 popped = self .q1.get() self .curr_size - = 1 # swap the names of two queues self .q = self .q1 self .q1 = self .q2 self .q2 = self .q def top( self ): # if no elements are there in q1 if ( self .q1.empty()): return # Leave one element in q1 and push others in q2 while ( self .q1.qsize() ! = 1 ): self .q2.put( self .q1.get()) # Pop the only left element from q1 to q2 top = self .q1.queue[ 0 ] self .q2.put( self .q1.get()) # swap the names of two queues self .q = self .q1 self .q1 = self .q2 self .q2 = self .q return top def size( self ): return self .curr_size # Driver Code if __name__ = = '__main__' : s = Stack() s.push( 1 ) s.push( 2 ) s.push( 3 ) s.push( 4 ) print ( "current size: " , s.size()) print (s.top()) s.pop() print (s.top()) s.pop() print (s.top()) print ( "current size: " , s.size()) # This code is contributed by jainlovely450 |
C#
using System; using System.Collections; class GfG { public class Stack { public Queue q1 = new Queue(); public Queue q2 = new Queue(); //Just enqueue the new element to q1 public void Push( int x) => q1.Enqueue(x); //move all elements from q1 to q2 except the rear of q1. //Store the rear of q1 //swap q1 and q2 //return the stored result public int Pop() { if (q1.Count == 0) return -1; while (q1.Count > 1) { q2.Enqueue(q1.Dequeue()); } int res = ( int )q1.Dequeue(); Queue temp = q1; q1 = q2; q2 = temp; return res; } public int Size() => q1.Count; public int Top() { if (q1.Count == 0) return -1; while (q1.Count > 1) { q2.Enqueue(q1.Dequeue()); } int res = ( int )q1.Dequeue(); q2.Enqueue(res); Queue temp = q1; q1 = q2; q2 = temp; return res; } }; public static void Main(String[] args) { Stack s = new Stack(); s.Push(1); Console.WriteLine( "Size of Stack: " + s.Size() + "\tTop : " + s.Top()); s.Push(7); Console.WriteLine( "Size of Stack: " + s.Size() + "\tTop : " + s.Top()); s.Push(9); Console.WriteLine( "Size of Stack: " + s.Size() + "\tTop : " + s.Top()); s.Pop(); Console.WriteLine( "Size of Stack: " + s.Size() + "\tTop : " + s.Top()); s.Pop(); Console.WriteLine( "Size of Stack: " + s.Size() + "\tTop : " + s.Top()); s.Push(5); Console.WriteLine( "Size of Stack: " + s.Size() + "\tTop : " + s.Top()); } } //Submitted by Sakti Prasad //Size of Stack: 1 Top : 1 //Size of Stack: 2 Top : 7 //Size of Stack: 3 Top : 9 //Size of Stack: 2 Top : 7 //Size of Stack: 1 Top : 1 //Size of Stack: 2 Top : 5 |
current size: 4 4 3 2 current size: 2
Method 3 (Using only 1 queue):
In this method we will be using only one queue and make the queue act as stack. The idea behind this approach is to make one queue and push the first element in it. After the first element, we push the next element and then push the first element again and finally pop the first element. So, according to the FIFO rule of queue, second element that was inserted will be at the front and then the first element as it was pushed again later and its first copy was popped out. So, this acts as a stack and we do this at every step i.e. from the initial element to the second last element and the last element will be the one which we are inserting and since we will be pushing the initial elements after pushing the last element, our last element becomes the first element.
C++
#include <bits/stdc++.h> using namespace std; // Stack Class that acts as a queue class Stack { queue< int > q; public : void push( int data); void pop(); int top(); bool empty(); }; // Push operation void Stack::push( int data) { // Get previous size of queue int s = q.size(); // Push the current element q.push(data); // Pop all the previous elements and put them after // current element for ( int i = 0; i < s; i++) { // Add the front element again q.push(q.front()); // Delete front element q.pop(); } } // Removes the top element void Stack::pop() { if (q.empty()) cout << "No elements\n" ; else q.pop(); } // Returns top of stack int Stack::top() { return (q.empty()) ? -1 : q.front(); } // Returns true if Stack is empty else false bool Stack::empty() { return (q.empty()); } int main() { Stack st; st.push(40); st.push(50); st.push(70); cout << st.top() << "\n" ; st.pop(); cout << st.top() << "\n" ; st.pop(); cout << st.top() << "\n" ; st.push(80); st.push(90); st.push(100); cout << st.top() << "\n" ; st.pop(); cout << st.top() << "\n" ; st.pop(); cout << st.top() << "\n" ; return 0; } |
70 50 40 100 90 80
References:
Implement Stack using Two Queues
This article is compiled by Sumit Jain and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.