题目如下:
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.
Notes:
You must use only standard operations of a queue – which means only push to back, peek/pop from front, size, and is 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).
题目大意:利用队列操作实现栈,要求只利用 队列的基本操作,入队,取队头元素等。
基本思路:和利用 栈实现队列的操作类似,需要两个对应的数据结构。这里我们利用两个队列,模拟入栈出栈操作。一个典型的入栈出栈例子如下: 队列q1 入队,a,b,c,d 元素,模拟出栈操作,需要弹出 d, 因此需要队列q1依次出队,进入q2, 当q1 中只剩下 d一个元素时,弹出d即可,入栈操作应该选择队列不为空的那一个,保证任何时刻必然有一个队列为空,给出栈操作留足空间。
特别注意:pop操作 和top操作 的区别:当top操作时,只取得队尾元素而pop操作需要取得队尾元素并删除,所以为了保证 出队队列在操作结束后为空,top操作需要保存队尾元素 然后 将其从出队队列中删除 ,并将保存的队尾元素插入到入队队列的末尾;pop操作则不需要保存队尾元素。
Java 实现的算法如下:
public class MyStack { private Queue<Integer> q1; private Queue<Integer> q2; /** Initialize your data structure here. */ public MyStack() { q1=new ArrayDeque<Integer>(); q2=new ArrayDeque<Integer>(); } /** Push element x onto stack. */ public void push(int x) { if(q1.size()==0) q2.add(x); else q1.add(x); } /** Removes the element on top of the stack and returns that element. */ public int pop() { if(q2.size()==0){ while(q1.size()>1) q2.add(q1.remove()); return q1.remove(); } else{ while(q2.size()>1) q1.add(q2.remove()); return q2.remove(); } } /** Get the top element. */ public int top() { int topValue; if(q2.size()==0){ while(q1.size()>1) q2.add(q1.remove()); topValue=q1.remove(); q2.add(topValue); } else{ while(q2.size()>1) q1.add(q2.remove()); topValue=q2.remove(); q1.add(topValue); } return topValue; } /** Returns whether the stack is empty. */ public boolean empty() { return q1.size()==0&&q2.size()==0; } } /** * 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(); * boolean param_4 = obj.empty(); */