/**
* 使用栈实现队列
* 思路:使用两个栈,加入元素是将值保存到栈A中,取出时将A的值全部放到B中,从B中出栈
* 时间复杂度:均摊时间复杂度为O(1)
*/
public class StackQueue {
private Stack<Integer> stackA = new Stack<>();
private Stack<Integer> stackB = new Stack<>();
/**
* 入队列
* @param data
*/
public void enQueue(Integer data){
stackA.push(data);
}
/**
* 取出元素
* @return
*/
public Integer deQueue(){
if(stackB.isEmpty()){
if(stackA.isEmpty()) {
return null;
}
transfer();
}
return stackB.pop();
}
/**
* 将栈A中的元素的值移到B栈中
*/
private void transfer(){
while (!stackA.isEmpty()) {
stackB.push(stackA.pop());
}
}
public static void main(String[] args) {
StackQueue stackQueue = new StackQueue();
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());
}
}