We are given queue data structure, the task is to implement stack using only given queue data structure.
We have discussed a solution that uses two queues. In this article, a new solution is discussed that uses only one queue. This solution assumes that we can find size of queue at any point. The idea is to keep newly inserted element always at rear of queue, keeping order of previous elements same. Below are complete steps.
// x is the element to be pushed and s is stack push(s, x) 1) Let size of q be s. 1) Enqueue x to q 2) One by one Dequeue s items from queue and enqueue them. // Removes an item from stack pop(s) 1) Dequeue an item from q
Below is implementation of the idea.
This article is contributed by Manu Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Implement Stack and Queue using Deque
- How to implement stack using priority queue or heap?
- Check if a queue can be sorted into another queue using a stack
- Stack and Queue in Python using queue Module
- How to efficiently implement k stacks in a single array?
- How to efficiently implement k Queues in a single array?
- Implement Stack using Queues
- Implement a stack using singly linked list
- Design and Implement Special Stack Data Structure | Added Space Optimized Version
- Difference between Array, Queue and Stack
- Check if moves in a stack or queue are possible or not
- Difference between Stack and Queue Data Structures
- Level order traversal in spiral form | Using one stack and one queue
- Stack Permutations (Check if an array is stack permutation of other)
- Infix to Postfix using different Precedence Values for In-Stack and Out-Stack
- Find maximum in stack in O(1) without using additional stack
- Stack | Set 3 (Reverse a string using stack)
- Sort a stack using a temporary stack
- Reversing a Queue using another Queue
- Implement two stacks in an array