首先,我们得知道队列和栈存储数据的特点:
队列:Queue是一种先进先出(First In First Out)的数据结构,只允许在队首进行删除操作,队尾进行插入操作。
栈 : Stack是一种后进先出(Last In First Out)的数据结构,只在栈顶操作。
由此可知,队列数据结构和栈正好相反,当用栈模拟队列时就要遵循队列先进先出的特点,因此,我们可以定义两个栈(一个入队栈,一个出队栈)来模拟队列。
思路:push过程:将元素push入stack1中即可
pop过程:如果stack2非空,则将stack2中元素pop出即可。如果stack2为空,则将stack1 中 所有元素依次压入stack2中。由于先进入队列的元素在stack1的底部,因此将会被放置到 stack2的顶部,最先pop出。
图解如下:
代码实现:
public class Test01 {
public static void main(String[] args) {
MyQueue queue = new MyQueue();
queue.offer("A1");
queue.offer("A2");
queue.offer("A3");
queue.offer("A4");
System.out.println(queue.poll() + "出队");
queue.offer("A5");
//遍历队列
while(!queue.isEmpty()) {
System.out.println(queue.poll());
}
}
}
//栈模拟队列
class MyQueue{
private Stack in = new Stack(); //入队栈
private Stack out = new Stack(); //出队栈
//判断队列是否为空
public boolean isEmpty() {
return in.size() == 0 && out.size() == 0;
}
//入队
public void offer(E e) {
while(!out.isEmpty()) {//判断出队栈是否为空
in.push(out.pop());
}
in.push(e);
}
//出队
public E poll() {
while(!in.isEmpty()) {
out.push(in.pop());
}
return out.pop();
}
}



