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) // x is the element to be pushed and s is stack 1) Enqueue x to q2 2) One by one dequeue everything from q1 and enqueue to q2. 3) Swap the names of q1 and q2 // Swapping of names is done to avoid one more movement of all elements // from q2 to q1. pop(s) 1) Dequeue an item from q1 and return it.
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) 1) Enqueue x to q1 (assuming size of q1 is unlimited). pop(s) 1) One by one dequeue everything except the last element from q1 and enqueue to q2. 2) Dequeue the last item of q1, the dequeued item is result, store it. 3) Swap the names of q1 and q2 4) Return the item stored in step 2. // Swapping of names is done to avoid one more movement of all elements // from q2 to q1.
current size: 4 4 3 2 current size: 2
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.
- How to efficiently implement k Queues in a single array?
- Implement a stack using single queue
- Implement Stack and Queue using Deque
- How to implement stack using priority queue or heap?
- Implement a stack using singly linked list
- Design and Implement Special Stack Data Structure | Added Space Optimized Version
- Stack Permutations (Check if an array is stack permutation of other)
- Infix to Postfix using different Precedence Values for In-Stack and Out-Stack
- Stack | Set 3 (Reverse a string using stack)
- Sort a stack using a temporary stack
- Level order traversal line by line | Set 2 (Using Two Queues)
- Implement two stacks in an array
- Implement PriorityQueue through Comparator in Java
- How to efficiently implement k stacks in a single array?
- Spaghetti Stack
Improved By : prerna saini