1、题目描述:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

2、思路:栈是先进后出,队列是先进先出。stack1只需要把其中的元素全部导入stack2 ,元素的顺序就变成了先进先出的顺序。但有一点必须考虑,那就是元素导入的时机问题,因为元素入队和出队的时机是随机的。最好的导入时机就是当想让元素pop出队的时候,若stack2为空,将stack1的元素全部导入进stack2。

       总之,这道题考的其实就是元素倒栈的时机。

3、代码:

import java.util.Stack;

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() {
        if(stack2.empty()){
            while(!stack1.empty()){
                stack2.push(stack1.pop());
            }


         }
        return stack2.pop();
    }
}
12-19 11:36
查看更多