题目:编写一个类,用两个栈实现队列,支持队列的基本操作。
思路:
选择两个栈,stackPush,stackPop,
队列入队时,入stackPush栈,
队列出队时,判断stackPop是否为空,不为空,直接在stackPop出栈,为空,则将stackPush栈中的所有元素全部添加到stackPop内,再出栈。
代码如下:
public class Main {
public Stack<Integer> stackPush;
public Stack<Integer> stackPop;
public Main(){
stackPush = new Stack<Integer>();
stackPop = new Stack<Integer>();
}
public void add(int pushInt){
stackPush.push(pushInt);
}
public int poll(){
if(stackPop.empty() && stackPush.empty()){
throw new RuntimeException("队列空");
}else if(stackPop.isEmpty()){
while(!stackPush.isEmpty()){
stackPop.push(stackPush.pop());
}
}
return stackPop.pop();
}
public int peek(){
if(stackPop.empty() && stackPush.empty()){
throw new RuntimeException("队列空");
}else if(stackPop.isEmpty()){
while(!stackPush.isEmpty()){
stackPop.push(stackPush.pop());
}
}
return stackPop.peek();
}
}