编写一个类,用两个栈实现队列,支持队列的基本操作(add、poll、peek)
add():增加一个元素
poll():移除并返回队列头部元素
peek():返回头部元素
public class TwoStackQueue{
public Stack<Integer> stackPush;
public Stack<Integer> stackPop;
public TwoStackQueue() {
stackPush = new Stack<Integer>();
stackPop = new Stack<Integer>();
}
/*两个栈组成队列需要注意两个错误:1:stackPush队列元素未完全放入stackPop中却
被压入新元素2:stackPop元素未清空却放入新元素。
*/
private void pushToPop(){
if (stackPop.empty()){
while (!stackPush.empty()){
stackPop.push(stackPush.pop());
}
}
}
//压入一个元素
public void add(int pushInt){
stackPush.push(pushInt);
pushToPop();
}
//返回并移除顶层元素
public void poll(){
if (stackPop.empty() && stackPush.empty()){
throw new runtimeException("Queue is empty!");
}
pushTopop();
return stackPop.pop();
}
//仅返回顶层元素
public void peek(){
if (stackPop.empty() && stackPush.empty()){
throw new runtimeException("Queue is empty!");
}
pushTopop();
return stackPop.peek();
}
}

京公网安备 11010502036488号