出队:最开始,stack2 里面是没有东西的,那么这时候就把 stack1 里面的所有元素依次 pop 出,并 push 入 stack1; 全部转移之后,处于 stack2 栈顶的就是最早进入 stack1 的元素,这时,对 stack2 进行 pop, 出去的就是最早进入队列(双栈)的元素;第一次之后,stack2 中已经有元素,此后每次 pop 只需要判断一下 stack2 是否为空,非空直接 pop ,为空则再转移一下
先进先出,完美实现
细节的判断看代码
代码
classSimulatedQueue{private Stack<Integer> stack1 =newStack<>();private Stack<Integer> stack2 =newStack<>();publicint size =0;//Stack1 as input collectionpublicvoidinsert(Integer i){
stack1.push(i);
size ++;}public Integer pop(){if(size <=0)return null;//Transfer all the elements from stack1 to stack2, then all the sequence are reversed.//So if we pop stack2 now, the first element pushed to stack1 are now popped first.//That's "first in , first out" just like queueif(stack2.size()<=0){int size1 = stack1.size();for(int i =0; i < size1; i ++){
stack2.push(stack1.pop());}}
size --;return stack2.pop();}}