队列是先进先出,栈是先进后出,所以如果想用栈实现队列的话,就可以使用一个栈当作压入栈,压入数据时,只往栈压入数据,记为stackPush,一个栈当作弹出栈,弹出数据时只从这个栈弹出,记作stackPop.但是需要注意以下几点:
- 如果stackPush要往stackPop中压入数据,必须一次性把stackPush中的数据全部压入
- 如果stackPop不为空,stackPush绝对不能向stackPop中压入数据
具体代码如下:
package twostackqueue;
import java.util.Stack;
public class TwoStackQueue {
private Stack<Integer> stackPush;
private Stack<Integer> stackPop;
public TwoStackQueue() {
stackPush = new Stack<Integer>();
stackPop = new Stack<Integer>();
}
// 入队列
public void add(int x) {
stackPush.push(x);
}
// 出队列
public int poll() {
if (stackPop.empty() && stackPush.empty()) {
throw new RuntimeException("the Queue is empty!");
} else if (stackPop.empty()) {
while (!stackPush.empty()) {
stackPop.push(stackPush.pop());
}
}
return stackPop.pop();
}
public int peek() {
if (stackPop.empty() && stackPush.empty()) {
throw new RuntimeException("the Queue is empty!");
} else if (stackPop.empty()) {
while (!stackPush.empty()) {
stackPop.push(stackPush.pop());
}
}
return stackPop.peek();
}
}