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 email@example.com. 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.
- How to implement stack using priority queue or heap?
- Implement Stack and Queue using Deque
- Stack and Queue in Python using queue Module
- Check if a queue can be sorted into another queue using a stack
- Implement Stack using Queues
- Implement a stack using singly linked list
- How to efficiently implement k stacks in a single array?
- How to efficiently implement k Queues in a single array?
- Reversing a Queue using another Queue
- Design and Implement Special Stack Data Structure | Added Space Optimized Version
- Level order traversal in spiral form | Using one stack and one queue
- Difference between Circular Queue and Priority Queue
- Stack | Set 3 (Reverse a string using stack)
- Sort a stack using a temporary stack
- Infix to Postfix using different Precedence Values for In-Stack and Out-Stack
- Find maximum in stack in O(1) without using additional stack
- Check if moves in a stack or queue are possible or not
- Difference between Stack and Queue Data Structures
- Difference between Array, Queue and Stack
- Stack Permutations (Check if an array is stack permutation of other)