用两个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 }

转载于:https://www.cnblogs.com/zhaojinxin/p/5410296.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值