public class QueueOfStack<T> {
private Stack<T> stackA = null;
private Stack<T> stackB = null;
public QueueOfStack() {
stackA = new Stack<T>();
stackB = new Stack<T>();
}
/**
* 入队
*
* @param obj
*/
public synchronized void inQueue(T obj) {
stackA.push(obj);
}
/**
* 出队
*
* @return
*/
public synchronized Object outQueue() {
if (stackA.isEmpty())
return null;
while (!stackA.isEmpty())
stackB.push(stackA.pop());
T t = stackB.pop();
while (!stackB.isEmpty()) {
stackA.push(stackB.pop());
}
return t;
}
/**
* 出队
*
* @return
*/
public synchronized T outQueueV2() {
if (stackB.isEmpty()) {
if (stackA.isEmpty())
return null;
while (!stackA.isEmpty()) {
stackB.push(stackA.pop());
}
}
return stackB.pop();
}
public static void main(String[] args) {
QueueOfStack<String> queue = new QueueOfStack<String>();
queue.inQueue("1");
queue.inQueue("2");
queue.inQueue("3");
System.out.println(queue.outQueueV2());
System.out.println(queue.outQueueV2());
System.out.println(queue.outQueueV2());
}
}
数据结构与算法之使用两个栈实现一个队列
最新推荐文章于 2020-12-08 05:10:28 发布