Implement Stack using Queues
Problem
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push
, top
, pop
, and empty
).
Implement the MyStack
class:
void push(int x)
Pushes element x to the top of the stack.int pop()
Removes the element on the top of the stack and returns it.int top()
Returns the element on the top of the stack.boolean empty()
Returnstrue
if the stack is empty,false
otherwise.
Follow-up: Can you implement the stack using only one queue?
Constraints
1 <= x <= 9
- At most
100
calls will be made topush
,pop
,top
, andempty
. - All the calls to
pop
andtop
are valid.
Solution
The problem Implement Stack using Queues
can be solved by using a queue to rotate previously pushed elements when a new push is called to simulate the order in which elements are stored in stack.
Implementation
class MyStack
{
private:
queue<int> _stack;
public:
MyStack() {}
void push(int x)
{
_stack.push(x);
for (int i = _stack.size(); i > 1; i--)
{
int front = _stack.front();
_stack.pop();
_stack.push(front);
}
}
int pop()
{
int ret = _stack.front();
_stack.pop();
return ret;
}
int top() { return _stack.front(); }
bool empty() { return _stack.empty(); }
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/