codeTop100题(39)232. 用栈实现队列

64 阅读1分钟

1. 题目

232. 用栈实现队列

2. 分析

由于只能使用栈,栈是一个先进先出的数据结构,题目要求实现队列,队列是一个先进后出的数据结构。

我们是否可以使用两个栈,先进后出+先进后出,是不是就等于先进先出了呢?

  1. 我们需要按1 2 3 4的顺序保证先进先出,首先把他们放到栈a中

image.png

  1. 当栈b为空的时候,把栈a的数全pop后push到栈b中

image.png

  1. 这个时候我们只需要pop栈b里面的数字就能实现先进先出了

注:栈b为空的时候才能push数哈,否则顺序会乱。

3. 代码

class MyQueue {

    Deque<Integer> deque = new ArrayDeque<>();
    Deque<Integer> deque1 = new ArrayDeque<>();
    public MyQueue() {
    }

    public void push(int x) {
        deque.push(x);
        move();
    }
    private void move() {
        if (deque1.isEmpty()) {
            while (!deque.isEmpty()) {
                deque1.push(deque.pop());
            }
        }
    }

    public int pop() {
        move();
        if (deque1.isEmpty()) {
            return -1;
        }
        return deque1.pop();
    }

    public int peek() {
        move();
        if (deque1.isEmpty()) {
            return -1;
        }
        return deque1.peek();
    }

    public boolean empty() {
        move();
        return deque1.isEmpty();
    }
}