leetcode 225. 用队列实现栈(维护两个队列用于倒替元素,使用和1进行按位与,实现队列切换)

题目

在这里插入图片描述

思路

维护两个队列,每一次 pop 或者 top 操作,都把当前队列的所有元素放进另外一个队列中(保留或查看最后一个元素,用于返回)
在这里插入图片描述

题解

class MyStack {
    ArrayList<LinkedList<Integer>> twoQueue = new ArrayList<>();// 里面放了两个队列
    int listNum = 0;//用来切换当前队列

    /**
     * Initialize your data structure here.
     */
    public MyStack() {
        LinkedList<Integer> list1 = new LinkedList<>();
        LinkedList<Integer> list2 = new LinkedList<>();
        twoQueue.add(list1);
        twoQueue.add(list2);
    }

    /**
     * Push element x onto stack.
     */
    public void push(int x) {
        twoQueue.get(listNum).add(x);
    }

    /**
     * Removes the element on top of the stack and returns that element.
     */
    public int pop() {
        LinkedList<Integer> anotherList = twoQueue.get(listNum ^ 1);
        LinkedList<Integer> curList = twoQueue.get(listNum);
        while (curList.size() > 1) {
            anotherList.add(curList.pop());
        }
        listNum ^= 1;//切换当前使用队列
        return curList.pop();
    }

    /**
     * Get the top element.
     */
    public int top() {
        LinkedList<Integer> anotherList = twoQueue.get(listNum ^ 1);
        LinkedList<Integer> curList = twoQueue.get(listNum);
        while (curList.size() > 1) {
            anotherList.add(curList.pop());
        }
        int ret = curList.pop();//先偷看一眼返回值
        anotherList.add(ret);//然后再放进去
        listNum ^= 1;
        return ret;
    }

    /**
     * Returns whether the stack is empty.
     */
    public boolean empty() {
        return twoQueue.get(listNum).isEmpty();
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/sinat_42483341/article/details/107702253