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

请指教交流!

 1 package com.it.hxs.c01;
 2 
 3 import java.util.Stack;
 4 
 5 /*
 6  编写一个类,用两个栈实现队列,支持队列的基本操作(add,poll,peek) 
 7  */
 8 public class HxsQueue {
 9 
10     public static void main(String args[]) {
11         HxsQueue demoQueue = new HxsQueue();
12         demoQueue.add("111");
13         demoQueue.add("222");
14         demoQueue.add("333");
15         demoQueue.poll();
16         System.out.println(demoQueue.peek());
17     }
18 
19     private Stack<String> pushStack;// 推入栈
20     private Stack<String> popStack;// 推出栈
21 
22     public HxsQueue() {
23         this.pushStack = new Stack<String>();
24         this.popStack = new Stack<String>();
25     }
26 
27     public void add(String content) {
28         if ("".equals(content) || content == null) {
29             throw new RuntimeException("添加的元素值不能为空!");
30         } else {
31             pushStack.push(content);
32             this.popStack = new Stack<String>();
33             for (int index = pushStack.size() - 1; index >= 0; index--) {
34                 popStack.push(pushStack.elementAt(index));
35             }
36         }
37     }
38 
39     public String poll() {
40         String result = "无元素";
41         if (!popStack.isEmpty()) {
42             result = popStack.pop();
43             this.pushStack = new Stack<String>();
44             for (int index = popStack.size() - 1; index >= 0; index--) {
45                 pushStack.push(popStack.elementAt(index));
46             }
47         }
48         return result;
49     }
50 
51     public String peek() {
52         String result = "无元素";
53         if (!popStack.isEmpty()) {
54             result = popStack.peek();
55         }
56         return result;
57     }
58 
59 }

 

转载于:https://www.cnblogs.com/chaoge516/p/7423624.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值