8.6:如何用栈结构实现队列结构
8.6:如何用栈结构实现队列结构
两栈:push栈 和 pop栈
倒数据的要求:
1、如果倒数据,必须一次性倒完。
2、如果pop栈不为空,不能倒数据。pop栈空了才能倒数据。
1 public static class TwoStacksQueue {
2 public Stack<Integer> stackPush;
3 public Stack<Integer> stackPop;
4
5 public TwoStacksQueue() {
6 stackPush = new Stack<Integer>();
7 stackPop = new Stack<Integer>();
8 }
9
10 // push栈向pop栈倒入数据
11 private void pushToPop() {
12 if (stackPop.empty()) {
13 while (!stackPush.empty()) {
14 stackPop.push(stackPush.pop());
15 }
16 }
17 }
18
19 public void add(int pushInt) {
20 stackPush.push(pushInt);
21 pushToPop();
22 }
23
24 public int poll() {
25 if (stackPop.empty() && stackPush.empty()) {
26 throw new RuntimeException("Queue is empty!");
27 }
28 pushToPop();
29 return stackPop.pop();
30 }
31
32 public int peek() {
33 if (stackPop.empty() && stackPush.empty()) {
34 throw new RuntimeException("Queue is empty!");
35 }
36 pushToPop();
37 return stackPop.peek();
38 }
39 }