/**
* @author zhangrichao
* @version 创建时间:2019年1月23日 上午10:39:15
* 用两个栈实现队列
*/
public class StatckQueue {
private Stack<Integer> stackA=new Stack<Integer>();
private Stack<Integer> stackB=new Stack<Integer>();
/*入队操作*/
public void enQueue(int element){
stackA.push(element);
}
/*出队操作*/
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) throws Exception{
StatckQueue stackQueue= new StatckQueue();
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());
}
}
用Java实现两个栈实现一个队列
最新推荐文章于 2024-07-10 22:06:07 发布