核心思想就是两个栈,协作实现队列的入队、出队操作
详细的分析见代码块
import java.util.Stack;
//用栈实现队列--->核心思想就是两个栈,协作实现队列的入队、出队操作。
public class StackToQueue {
//声明两个栈,A作为入队使用,B作为出队使用。
private static Stack<Integer> stackA=new Stack<Integer>();
private static Stack<Integer> stackB=new Stack<Integer>();
//入队操作--->A负责入队,所以调用A的push()
public void enQueue(int element) {
stackA.push(element);
}
//出队操作--->B负责出队,所以调用B的pop()
public Integer deQueue() {
if(stackB.isEmpty()) {//stackB如果为空,就要先进行stackATOstackB()的交换入栈操作
if(stackA.isEmpty()) {//如果A,B都为空,那就直接返回null
return null;
}
stackATOstackB();//B空,A不空,进行 A-->B 的交换(A出栈,B入栈)工作
}
return stackB.pop();
}
//A到B的交换
private void stackATOstackB() {
// TODO Auto-generated method stub
while(!stackA.isEmpty()) {
stackB.push(stackA.pop());
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
StackToQueue stackQueue = new StackToQueue();
stackQueue.enQueue(1);
stackQueue.enQueue(2);
stackQueue.enQueue(3);
System.out.println(stackQueue.deQueue());
System.out.println(stackQueue.deQueue());
stackQueue.enQueue(4);
System.out.println(stackQueue.deQueue());
System.out.println(stackQueue.deQueue());
}
}