题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
这道题目很简单,不能使用其他数据结构,这里我们将一个栈作为队列入队,另一个栈作为出队。可知,队列入队顺序与栈出顺序相反。
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {//在pop之前 将一个栈中元素全部pop 然后push到另一个栈 再另一个栈pop
if(stack2.isEmpty()) {
while(!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
return stack2.pop();
}
else {
return stack2.pop();
}
}
}
我们只需判断作为出队的栈是否为空,如果为空,将入队全部push进出队栈即可。如果不为空,显然直接pop出队栈即可。