由两个栈组成队列

【题目】

             编写一个类,用两个栈实现队列,支持队列的基本操作(add、poll、peek)。

【解答】​

            栈的特点是先进后出,而队列的特点是先进先出。我们用两个栈正好能把顺序反过来实现类似队列的操作。

            具体实现上,是把一个栈作为压入栈,在压入数据时只往这个栈中压入,记为stackPush;另一个栈只作为弹出栈,在弹出数据时只从这个栈中弹出,记为stackPop。

            因为数据压入栈的时候,顺序是先进先出的。那么只要把stackPush的数据再次压入stackPop中,顺序就变回来了。

将1-5依次压入stackPush,那么从stackPush的栈顶到栈底为5~1,此时依次再将5~1倒入stackPop,那么从stackPop的栈顶到栈底就变成了1~5.再从stackPop中弹出,顺序就和队列一样了。​

            BUT,要做到以下两点:

           (1)如果stackPush要往stackPop中压入数据,那么必须一次性把stackPush中的数据全部压入。

            (2)如果stackPop不为空,stackPush绝对不能向stackPop中压入数据。

            违反以上两点都会发生错误。

【代码】

TwoStackQueue.java:

 1 package cn.hl.p2;
 2 
 3 import java.util.Stack;
 4 /**
 5  * 题目:由两个栈组成的队列
 6  * 要求:用两个栈实现队列,支持队列的基本操作(add、poll、peek)
 7  * @author 猩生柯北
 8  *
 9  */
10 public class TwoStackQueue {
11     public Stack<Integer> stackPush;
12     public Stack<Integer> stackPop;
13     
14     public TwoStackQueue(){
15         stackPush = new Stack<Integer>();
16         stackPop = new Stack<Integer>();
17     }
18     
19     public void add(int pushInt){
20         stackPush.push(pushInt);
21     }
22     
23     public int poll(){
24         if(stackPop.empty() && stackPush.empty()){
25             throw new RuntimeException("Queue is empty!");
26         }else if(stackPop.empty()){
27             while(!stackPush.empty()){
28                 stackPop.push(stackPush.pop());
29             }
30         }
31         return stackPop.pop();
32     }
33     
34     public int peek(){
35         if(stackPop.empty() && stackPush.empty()){
36             throw new RuntimeException("Queue is empty!");
37         }else if(stackPop.empty()){
38             while(!stackPush.empty()){
39                 stackPop.push(stackPush.pop());
40             }
41         }
42         return stackPop.peek();
43     }
44 }

Test.java:

 1 package cn.hl.p2;
 2 
 3 public class Test {
 4     public static void main(String[] args) {
 5         TwoStackQueue tsq = new TwoStackQueue();
 6         tsq.add(3);
 7         tsq.add(8);
 8         tsq.add(-5);
 9         tsq.add(0);
10         tsq.add(8);
11         System.out.print("输出队列的head元素:");
12         System.out.println(tsq.peek());
13         System.out.println("===========");
14         System.out.println(tsq.poll());
15     }
16 
17 }

【运行结果】

 

posted @ 2018-09-02 16:51  猩生柯北  阅读(162)  评论(0编辑  收藏  举报