栈的特点是:后进先出(Last In First Out)
队列的特点是:先进先出(First In First Out)
用栈模拟队列的思路:先定义两个栈in和out,用栈in来存储元素,栈out来输出元素,入队时按顺序压入栈in中,再从栈in中弹出压入到栈out中,这样根据栈的特点,按顺序将栈out的元素出栈就好了。具体实现如下:
public static void main(String[] args) {
MyQueue<String> queue = new MyQueue<String>();
queue.offer("A1");
queue.offer("A2");
queue.offer("A3");
queue.offer("A4");
queue.offer("A5");
System.out.println(queue.poll() + "出队");
// 遍历
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
}
}
//用栈模拟队列
class MyQueue<E> {
private Stack<E> in = new Stack<E>(); // 入队栈
private Stack<E> out = new Stack<E>(); // 出队栈
// 入队
public void offer(E e) {
while (!out.isEmpty()) {
in.push(out.pop());
}
in.push(e);
}
public boolean isEmpty() {
return in.size() == 0 && out.size() == 0;
}
// 出队
public E poll() {
while (!in.isEmpty()) {
out.push(in.pop());
}
return out.pop();
}
注意:在入队时确保栈out里面没有元素,即全部放入栈in中,出队时也要保证栈in里面也没有元素,也就是全部出队!!