Suppose we have two stacks and no other temporary variable.
Is to possible to "construct" a queue data structure using only the two stacks?
Suppose we have two stacks and no other temporary variable.
Is to possible to "construct" a queue data structure using only the two stacks?
here is my solution in java using linkedlist.
}
Note : In this case, pop operation is very time consuming. So i won't suggest to create a queue using two stack.
With
O(1)
dequeue()
, which is same as pythonquick's answer:With
O(1)
enqueue()
(this is not mentioned in this post so this answer), which also uses backtracking to bubble up and return the bottommost item.Obviously, it's a good coding exercise as it inefficient but elegant nevertheless.
Queue implementation using two java.util.Stack objects:
Keep 2 stacks, let's call them
inbox
andoutbox
.Enqueue:
inbox
Dequeue:
If
outbox
is empty, refill it by popping each element frominbox
and pushing it ontooutbox
Pop and return the top element from
outbox
Using this method, each element will be in each stack exactly once - meaning each element will be pushed twice and popped twice, giving amortized constant time operations.
Here's an implementation in Java:
A solution in c#
Two stacks in the queue are defined as stack1 and stack2.
Enqueue: The euqueued elements are always pushed into stack1
Dequeue: The top of stack2 can be popped out since it is the first element inserted into queue when stack2 is not empty. When stack2 is empty, we pop all elements from stack1 and push them into stack2 one by one. The first element in a queue is pushed into the bottom of stack1. It can be popped out directly after popping and pushing operations since it is on the top of stack2.
The following is same C++ sample code:
This solution is borrowed from my blog. More detailed analysis with step-by-step operation simulations is available in my blog webpage.