题目链接:https://leetcode.com/problems/implement-queue-using-stacks/
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
class Queue {
private:
stack<int> _old,_new;
public:
void shiftStack()
{
if(_old.empty())
{
while(!_new.empty())
{
_old.push(_new.top());
_new.pop();
}
}
}
void push(int x)
{
_new.push(x);
}
void pop(void)
{
shiftStack();
if(!_old.empty())
_old.pop();
}
int peek(void)
{
shiftStack();
if(!_old.empty())
return _old.top();
return 0;
}
bool empty(void)
{
return _old.empty() && _new.empty();
}
};