用栈实现队列
public static class TwoStacksQueue{
public Stack<Integer> stackPush;
public Stack<Integer> stackPop;
public TwoStacksQueue(){//构造方法
stackPush=new Stack<>();
stackPop=new Stack<>();
}
//将push栈中数据倒入pop栈中 要满足两个条件
private void pushToPop(){
if(stackPop.empty()){
while (!stackPush.empty()){
stackPop.push(stackPush.pop());
}
}
}
public void add(int pushInt){
stackPush.push(pushInt);
pushToPop();
}
public int poll(){//元素出队
if(stackPop.empty() && stackPush.empty()){
throw new RuntimeException("Queue is empty!");
}
pushToPop();
return stackPop.pop();
}
public int peek(){//取元素
if(stackPop.empty() && stackPush.empty()){
throw new RuntimeException("Queue is empty!");
}
pushToPop();
return stackPop.peek();
}
}