232. 用栈实现队列|刷题打卡

132 阅读2分钟

一、题目描述:

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列的支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false

说明:

  • 你只能使用标准的栈操作 —— 也就是只有 push to toppeek/pop from topsize, 和 is empty 操作是合法的。
  • 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。

示例:

输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]

解释:

MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

二、思路分析:

思路一:

使用两个栈来实现队列。栈:先进后出;队列:先进先出。我们可以将两个栈一个作为进inList、一个作为出outList。
实现队列push:在队列中先进的元素先出,那就直接push到inList栈。
此元素应该是出栈中最先出来的。当outList为空时,将进栈inList里面的元素push到outList;
pop:弹出最先进的元素并返回元素:outList直接弹出即可;
peek:队列开头元素:目标元素即outList中最后一个元素。
empty:直接判断进、出栈是否为空。

三、AC 代码:

方法一:

class MyQueue {
    inList: number[];
    outList: number[];
    constructor() {
        this.inList = [];
        this.outList = [];
    }

    push(x: number): void {
        this.inList.push(x);
    }

    pop(): number {
        if (!this.outList.length) {
            while (this.inList.length) {
                this.outList.push(this.inList.pop());
            }
        }
        return this.outList.pop();
    }

    peek(): number {
        if (!this.outList.length) {
            while (this.inList.length) {
                this.outList.push(this.inList.pop());
            }
        }
        return this.outList[this.outList.length - 1]
    }

    empty(): boolean {
        return this.inList.length === 0 && this.outList.length === 0;
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * var obj = new MyQueue()
 * obj.push(x)
 * var param_2 = obj.pop()
 * var param_3 = obj.peek()
 * var param_4 = obj.empty()
 */

四、总结:

此题考查栈和队列的转换,只要掌握栈和队列核心原理即可。

题目来源:leetcode。
本文正在参与「掘金 2021 春招闯关活动」, 点击查看 活动详情