使用2个栈模拟队列的功能
import java.util.Stack;
/**
* 使用2个栈模拟队列
* 队列:先进先出
* 栈:先进后出
* 根据2着特性就可以直到用2个栈可以模拟一个队列
* 一个栈做插入栈,一个栈做弹出栈,弹出的时候,将插入栈的元素依次出栈,入栈到弹出栈中,这时弹出栈的顺序是:
* 先进插入栈的在弹出栈栈顶,那么依次将弹出栈的元素出栈,就可以实现先进先出了
*
*/
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyQueue queue = new MyQueue();
int[] data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
//入队
System.out.println("入队顺序");
for(int i : data){
queue.add(i);
System.out.print(i+" ");
}
System.out.println("");
System.out.println("出队顺序");
while(!queue.isEmpty()){
System.out.print(queue.remove()+" ");
}
/**
* 输出结果:
* 入队顺序
0 1 2 3 4 5 6 7 8 9 10
出队顺序
0 1 2 3 4 5 6 7 8 9 10
*/
}
}
class MyQueue{
Stack<Integer> insert = new Stack<Integer>();
Stack<Integer> remove = new Stack<Integer>();
//入队操作
public void add(Integer i){
insert.push(i);
}
//出对操作
public Integer remove(){
//如果弹出栈不是空的,直接弹出
if(!remove.isEmpty()){
int top = remove.pop();
return top;
}else{
//弹出栈为空,需要经插入栈依次出栈,然后入栈弹出栈,在从弹出栈弹出栈顶元素
if(insert.isEmpty()){
//插入栈也没有元素了,此时操作为非法
return insert.pop();
}else{
while(!insert.isEmpty()){
remove.push(insert.pop());
}
return remove.pop();
}
}
}
//判空操作
public boolean isEmpty(){
//插入和弹出栈同时为空才能为空
return insert.isEmpty() && remove.isEmpty();
}
}