题目:
编写一个类,用两个栈实现队列,支持队列的基本操作(add,poll,peek)
思路:
1、定义两个栈 pushStack, popStack;
2、将数据先压入 pushStack,然后将 pushStack 中的数据倒入 popStack,然后从 popStack中取数据,即类似队列的先进先出
注意:pushStack 中的数据应该一次性倒入 popStack,否则顺序将错误
当 popStack 中有数据时不能压入,否则顺序将错误
public class TwoStackQueue {public Stack<Integer> pushStack;public Stack<Integer> popStack;public void pushToPop() {if (popStack.isEmpty()) {while (!pushStack.isEmpty()) {popStack.push(pushStack.pop());}}}public void add(Integer value) {pushStack.push(value);pushToPop();}public Integer poll() {if (popStack.isEmpty() && pushStack.isEmpty()) {throw new NullPointerException("queue is empty");}pushToPop();return popStack.pop();}public void peek() {if (popStack.isEmpty() && pushStack.isEmpty()) {throw new NullPointerException("queue is empty");}pushToPop();popStack.peek();}
}