请指教交流!
package com.it.hxs.c01; import java.util.Stack; /*
编写一个类,用两个栈实现队列,支持队列的基本操作(add,poll,peek)
*/
public class HxsQueue { public static void main(String args[]) {
HxsQueue demoQueue = new HxsQueue();
demoQueue.add("111");
demoQueue.add("222");
demoQueue.add("333");
demoQueue.poll();
System.out.println(demoQueue.peek());
} private Stack<String> pushStack;// 推入栈
private Stack<String> popStack;// 推出栈 public HxsQueue() {
this.pushStack = new Stack<String>();
this.popStack = new Stack<String>();
} public void add(String content) {
if ("".equals(content) || content == null) {
throw new RuntimeException("添加的元素值不能为空!");
} else {
pushStack.push(content);
this.popStack = new Stack<String>();
for (int index = pushStack.size() - 1; index >= 0; index--) {
popStack.push(pushStack.elementAt(index));
}
}
} public String poll() {
String result = "无元素";
if (!popStack.isEmpty()) {
result = popStack.pop();
this.pushStack = new Stack<String>();
for (int index = popStack.size() - 1; index >= 0; index--) {
pushStack.push(popStack.elementAt(index));
}
}
return result;
} public String peek() {
String result = "无元素";
if (!popStack.isEmpty()) {
result = popStack.peek();
}
return result;
} }