用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();//stack类:栈(先进后出)
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);//入栈操作
}
public int pop() {
//判断栈是否为空
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();//出栈操作
}
}
思路:队列是先进先出,添加元素放在栈1;删除元素先判断栈2是否为空,为空则将栈1元素移动到栈2,从栈2移除元素!