import java.util.*;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
StackAndQueue sta = new StackAndQueue();
sta.offer(0);
sta.offer(1);
sta.offer(2);
sta.offer(3);
sta.offer(4);
sta.offer(5);
while(!sta.isEmpty()){
System.out.print(sta.remove()+" ");
}
}
}
class StackAndQueue{
//用两个栈互相颠倒来用栈实现队列
//约定 ,一个栈用来进元素 ,一个栈用来出元素
//出元素的时候,如果pop为空 把push栈里的元素全部倒进去 再出元素
Stack<Integer> stackPush ;
Stack<Integer> stackPop ;
public StackAndQueue(){
stackPush = new Stack<Integer>();
stackPop = new Stack<Integer>();
}
public boolean offer(int data){//插入队列
stackPush.push(data);
return true;
}
public int remove(){//移除队列头元素
if(stackPop.isEmpty()){
if(stackPush.isEmpty()){
throw new RuntimeException("Queue is empty!");
}else{
while(!stackPush.isEmpty()){
stackPop.add(stackPush.pop());
}
}
}
return stackPop.pop();
}
public int peek(){
if(stackPop.isEmpty()){
if(stackPush.isEmpty()){
throw new RuntimeException("Queue is empty!");
}else{
while(!stackPush.isEmpty()){
stackPush.add(stackPush.pop());
}
}
}
return stackPop.peek();
}
public boolean isEmpty(){
return stackPush.isEmpty()&&stackPop.isEmpty();
}
}
用栈模拟队列
最新推荐文章于 2024-09-06 08:55:11 发布