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();
}
}用栈模拟队列
最新推荐文章于 2023-06-10 08:36:05 发布
本文介绍了一种使用两个栈来模拟队列操作的方法。通过将一个栈用于元素的插入,另一个栈用于元素的移除,实现了队列的基本功能:offer(插入)、remove(移除)和peek(查看队首元素)。当移除元素时,如果负责移除操作的栈为空,则将负责插入操作的栈中所有元素倒入移除栈中。
283

被折叠的 条评论
为什么被折叠?



