用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
- 固定栈1入队,栈2出队。pop() 操作时,①如果两栈都为空,报异常;②如果出队栈有元素就出队;③如果出队栈为空,就把入队栈的元素都弹过来再出队。
import java.util.Stack;
public class s {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
while (stack1.isEmpty() && stack2.isEmpty()) {
throw new RuntimeException("Queue is empty");
}
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}