剑指offer编程题--用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

首先看图大概知道考察的是队列和栈基本知识,需要知道jdk的stack的方法的使用,以及栈先进后出,队列先进先出的知识

栈先进后出,队列先进先出

stack1.push(1);
stack1.push(2);
stack1.push(5);

上面这样顺序存储的化栈的输出是:521,队列就是:125

栈的基本方法:push存数据,pop只能取出栈顶并移除顶部

思考:调用push的时候stack1存1,2,5以后,再调用pop的时候,我们从stack1取,那肯定是5,2,1的顺序,然后存到stack2里就是5,2,1的顺序,那么我再取出stack2的数据,自然就是1,2,5跟队列一样的输出。

    static Stack<Integer> stack1 = new Stack<>();
    static Stack<Integer> stack2 = new Stack<>();
    

    public static void push(int node) {
        stack1.push(node);
    }

    public static int pop() {
        while (!stack1.empty()) {
            stack2.push(stack1.pop());
        }
        int take = stack2.pop();
        return take;
    }
 public static void main(String[] args) {
        stack1.push(1);
        stack1.push(2);
        stack1.push(5);
        int i = 0;
        while (i < 3) {
            i = i + 1;
            System.out.println(StackImplQueue.pop());
        }

    }

输出

猜你喜欢

转载自blog.csdn.net/dfBeautifulLive/article/details/106788475