基本思想:一个栈存放入队数据,另一个栈存放出队数据。出队时,出队栈为空的情况下,就一次性将入队栈的数据拿过来;出队栈不为空则pop出栈顶数据。
public class Queue<T> {
private Stack<T> inStack;
private Stack<T> outStack;
public void add(T t) {
if (inStack == null) {
inStack = new Stack();
}
inStack.push(t);
}
public T remove() {
if (outStack != null && outStack.size() > 0) {
return outStack.pop();
} else {
if (inStack == null) {
return null;
}
if (outStack == null) {
outStack = new Stack();
}
while (inStack.size() > 0) {
outStack.push(inStack.pop());
}
return outStack.pop();
}
}
public int size() {
return (inStack == null ? 0 : inStack.size()) + (outStack == null ? 0 : outStack.size());
}
}
stack用的是自己实现的,用jdk自带的也一样,未考虑复杂情况和多线程安全问题