栈实现队列
程序员文章站
2024-03-18 12:04:28
...
package test.com;
import java.util.Stack;
/**
* 1.栈实现队列
*/
public class Hui03_StackToQueue {
/*
使用两个栈实现队列
*/
public Stack<Integer> pushStack = new Stack<>(); //用来入队列
public Stack<Integer> popStack = new Stack<>(); //用来出队列
public void enQueue(Integer data){
pushStack.push(data);
}
public Integer deQueue(){
//当popStack为空时,要全部将pushStack栈中元素弹出,并压入到popStack中
if(popStack.isEmpty()){
if(pushStack.isEmpty()){
return null;
}
while (!pushStack.isEmpty())
popStack.push(pushStack.pop());
}
//否则,说明popStack不为空,直接弹出即可
return popStack.pop();
}
public static void main(String[] args) {
Hui03_StackToQueue queue = new Hui03_StackToQueue();
queue.enQueue(1);
queue.enQueue(9);
queue.enQueue(7);
System.out.println(queue.deQueue());
queue.enQueue(4);
System.out.println(queue.deQueue());
queue.enQueue(5);
System.out.println(queue.deQueue());
}
}
上一篇: 操作系统 页面置换算法实现
下一篇: 线性结构之----队列