二、 编写一个类,用两个栈实现队列,支持队列的基本操作(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