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.
- 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
- Zig Zag Level order traversal of a tree using single queue
- Implement a stack using singly linked list
- Check if moves in a stack or queue are possible or not
- Design and Implement Special Stack Data Structure | Added Space Optimized Version
- Difference between Stack and Queue Data Structures
- Level order traversal in spiral form | Using one stack and one queue
- Infix to Postfix using different Precedence Values for In-Stack and Out-Stack
- Stack Permutations (Check if an array is stack permutation of other)