思想比较简单,队列先进先出,我们要实现两个操作,进队和出队;
手里有2个栈,名为s1,s2。
那么进队的时候:只从进s1,即s1.push即可;
出队的时候:只从s2出。如果s2有元素的话,出栈即可;如果没有的话,令s1全部元素出栈,放入s2,返回s2.pop;
具体实现如下:
import java.util.Stack;
public class Solution {
Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>();
public void push(int node) {
s1.push(node);
}
public int pop() {
while(!s2.isEmpty()){
return s2.pop();
}
while(!s1.isEmpty()){
s2.push(s1.pop());
}
return s2.pop();
}
}