lc-225


请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(pushtoppopempty)。

实现 MyStack 类:

  • void push(int x) 将元素 x 压入栈顶。
  • int pop() 移除并返回栈顶元素。
  • int top() 返回栈顶元素。
  • boolean empty() 如果栈是空的,返回 true ;否则,返回 false

注意:

  • 你只能使用队列的基本操作 —— 也就是 push to backpeek/pop from frontsizeis empty 这些操作。
  • 你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。

示例:

输入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]

解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False

提示:

  • 1 <= x <= 9
  • 最多调用100pushpoptopempty
  • 每次调用 poptop 都保证栈不为空

进阶:你能否仅用一个队列来实现栈。


//leetcode submit region begin(Prohibit modification and deletion)
class MyStack {
    private Queue<Integer> q1;
    private Queue<Integer> q2;

    public MyStack() {
        q1 = new LinkedList<>();
        q2 = new LinkedList<>();
    }

    public void push(int x) {
        if (q1.isEmpty()) {
            q2.add(x);
        } else {
            q1.add(x);
        }
    }

    public int pop() {
        Queue<Integer> outQ = q1.isEmpty() ? q2 : q1;
        Queue<Integer> inQ = q1.isEmpty() ? q1 : q2;

        while (outQ.size() > 1) {
            inQ.add(outQ.poll());
        }

        if (!outQ.isEmpty()) {
            return outQ.poll();
        } else {
            return -1;
        }
    }

    public int top() {
        Queue<Integer> outQ = q1.isEmpty() ? q2 : q1;
        Queue<Integer> inQ = q1.isEmpty() ? q1 : q2;
        while (outQ.size() > 1) {
            inQ.add(outQ.poll());
        }

        if (!outQ.isEmpty()) {
            int last = outQ.poll();
            inQ.add(last);
            return last;
        } else {
            return -1;
        }
    }

    public boolean empty() {
        return q1.isEmpty() && q2.isEmpty();
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !