Implement the following operations of a stack using queues.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- empty() -- Return whether the stack is empty.
- You must use only standard operations of a queue -- which means only
push to back
,peek/pop from front
,size
, andis empty
operations are valid. - Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
- You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.
用队列实现栈,队列先进先出,栈后进先出,使用两个队列来回把元素搬移,就实现了,假设队列为Q1,Q2,
如果栈依次进行以下操作:push(1),push(2),push(3),相应的队列情况:
Q1 | 1 | EMPTY | 321 |
Q2 | EMPTY | 21 | EMPTY |
也就是每次找空的队列先把新元素入队,然后把另一个队列里所有元素出队并入队到当前队列,对应栈的push操作。
pop操作对应非空队列的出列操作。
class MyStack
{
ArrayDeque<Integer> q1,q2;
public MyStack()
{
q1=new ArrayDeque<>();
q2=new ArrayDeque<>();
}
public void push(int x)
{
if(empty())
q1.add(x);
else
{
if(q1.isEmpty())
{
q1.add(x);
while(!q2.isEmpty())
q1.add(q2.poll());
}
else {
q2.add(x);
while(!q1.isEmpty())
q2.add(q1.poll());
}
}
}
public void pop()
{
if(!empty())
{
if(!q1.isEmpty())
q1.poll();
else {
q2.poll();
}
}
}
public int top()
{
if(!q1.isEmpty())
return q1.peek();
return q2.peek();
}
public boolean empty()
{
return q1.isEmpty()&&q2.isEmpty();
}
}