题目
编写一个类, 用两个栈实现队列, 支持队列的基本操作(add, poll, peek).
思路
栈是FILO, 队列是FIFO.
一个栈stackPush按用户操作顺序存储, 提供入队操作.
另一个栈stackPop按照相反顺序存储, 提供出队操作.
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| public class TwoStacksQueue { private Stack<Integer> stackPush; private Stack<Integer> stackPop;
public TwoStacksQueue() { stackPush = new Stack<Integer>(); stackPop = new Stack<Integer>(); }
private void pushToPop() { if (stackPop.isEmpty()) { while (!stackPush.isEmpty()) { stackPop.push(stackPush.pop()); } } }
public void add(int item) { stackPush.push(item); pushToPop(); }
public int poll() { if (stackPush.isEmpty() && stackPop.isEmpty()) { throw new RuntimeException("Your queue is empty."); } pushToPop(); return stackPop.pop(); }
public int peek() { if (stackPush.isEmpty() && stackPop.isEmpty()) { throw new RuntimeException("Your queue is empty."); } pushToPop(); return stackPop.peek(); } }
|