两个栈实现队列
题目
用两个栈实现一个队列
思路
一个栈入队,一个栈出队,在出队之前要让入队的那个栈置空,也就是全部移到出队的那个栈。
代码
public class twoStackImpQuene {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
public void push(int n){
stack1.push(n);
}
public int pop(){
if (stack1.isEmpty()&&stack2.isEmpty()){
throw new RuntimeException("empty");
}else if (stack2.isEmpty()){
while (!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}