用两个Stack来实现一个Queue

 1 import java.util.Stack;
 2 
 3 /**
 4  * 问题:用两个Stack来实现一个Queue;
 5  * 方法:栈的特点是先进后出;而队列的特点是先进先出;
 6  *     用两个栈正好能把顺序调过来;
 7  *     一个栈,作为压入栈,在压入数据时,只往这个栈里压入,记作:stackPush;
 8  *     一个栈 ,作为弹出栈,在弹出数据时,只从这个栈里弹出,记作:stackPop;
 9  *
10  */
11 public class TwoStackQueue {
12     private Stack<Integer> stackPush;
13     private Stack<Integer> stackPop;
14     
15     public TwoStackQueue(){
16         this.stackPush = new Stack<Integer>();
17         this.stackPop = new Stack<Integer>();
18     }
19     
20     //向队列中添加元素;
21     public void add(int pushInt) {
22         stackPush.push(pushInt);
23     }
24     
25     //从队列中删除元素;
26     public int poll() {
27         if(stackPop.empty() && stackPush.empty()) {
28             throw new RuntimeException("Queue is empty!");
29         } else if(stackPop.empty()) {
30             while(!stackPush.empty()) {
31                 stackPop.push(stackPush.pop());
32             }
33         }
34         return stackPop.pop();
35     }
36     
37     //得到位于队头位置元素的值;
38     public int peek() {
39         if(stackPop.empty() && stackPush.empty()) {
40             throw new RuntimeException("Queue is empty!");
41         } else if(stackPop.empty()) {
42             while(!stackPush.empty()) {
43                 stackPop.push(stackPush.pop());
44             }
45         }
46         return stackPop.peek();
47         
48     }
49     
50     //测试程序
51     public static void main(String[] args) {
52         TwoStackQueue tsq = new TwoStackQueue();
53         int[] a = {1, 2, 3, 4, 5, 6, 7};
54         for(int i: a){
55             tsq.add(i);
56         }
57         
58         for(int j=0; j<a.length; j++) {
59             int num = tsq.peek();
60             tsq.poll();
61             System.out.println(num);
62         }
63     }
64     
65 }

posted @ 2016-04-19 21:44  简笔话_Golden  阅读(640)  评论(0编辑  收藏  举报