题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
分析:一般都是以下方法实现
入队操作只需要在一个栈中执行push操作即可;
出队操作,需要将栈1中的元素加入到栈2中,再执行pop操作;若栈2为空,出队操作就需要转移元素,若不为空直接出栈即可。
实现:
class myQueue{
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node){
stack1.push(node);
}
public int pop(){
if(stack1.empty() && stack2.empty()) {
throw new RuntimeException("栈为空!!!");
}
//若栈2为空,则需要将栈1中的元素转移到栈2中
if(stack2.empty()){
while (!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}