本文章实现栈模拟队列
class MyQueue<E> {
// 定义两个栈,分别用于入队和出队
private Stack<E> inStack;
private Stack<E> outStack;
// 构造方法
public MyQueue() {
inStack = new Stack<E>();
outStack = new Stack<E>();
}
// 入队
public void offer(E item) {
while (!outStack.isEmpty()) {
inStack.push(outStack.pop());
}
inStack.push(item);
}
// 出队
public E pop() {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
return outStack.pop();
}
// 判断是否为空
public boolean isEmpty() {
return (inStack.size() == 0 && outStack.size() == 0);
}
}
想要使用栈模拟队列,要队列先进先出的特性,即最先入栈的要最先出来,所以要满足先入栈的元素是最先入队的元素,所以使用两个栈,inStack用于入队:当入队时,先判断outStack栈中元素是否全部入栈到inStack,若没有则将outStack栈中的元素全部入栈到inStack队列中,若已全入栈完,则最新的元素当inStack的栈尾元素;outStack用于出队:先将inStack队列中的元素全部入队到outStack队列中,即最新的元素outStack栈的栈头,再将outStack栈的元素压出去,即达到了队列的先进先出的效果。
效果展示: