「前端刷题」225.用队列实现栈(EASY)

58 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第24天,点击查看活动详情

题目(Implement Stack using Queues)

链接:https://leetcode-cn.com/problems/implement-stack-using-queues
解决数:5221
通过率:67.5%
标签:栈 设计 队列 
相关公司:amazon bytedance microsoft 

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

实现 MyStack 类:

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

 

注意:

  • 你只能使用队列的基本操作 —— 也就是 push to backpeek/pop from frontsize 和 is 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
  • 最多调用100 次 pushpoptop 和 empty
  • 每次调用 pop 和 top 都保证栈不为空

 

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

思路

push 方法入队1,出队时将队1元素依次出队,放入队2中,将队1中最后一个元素推出。然后再将队2元素依次放回到队1中。

代码

var MyStack = function() {
    this.queue = [];
    this._queue = [];
};

MyStack.prototype.push = function(x) {
    this.queue.push(x);
};

MyStack.prototype.pop = function() {
    while(this.queue.length > 1){
        this._queue.push(this.queue.shift());
    }
    let ans = this.queue.shift();
    while(this._queue.length){
        this.queue.push(this._queue.shift());
    }
    return ans;
};

MyStack.prototype.top = function() {
    return this.queue.slice(-1)[0];
};

MyStack.prototype.empty = function() {
    return !this.queue.length;
};

思路2

设置两个队列queue1queue2, 把每次push的元素放入queue2中,然后再将queue1队列出队,依次放入queue2中,这样新入队元素就排在了queue2的队首,最后我们将queue1queue2交换。

代码

var MyStack = function() {
    this.queue = [];
    this._queue = [];
};

MyStack.prototype.push = function(x) {
    this._queue.push(x);
    while (this.queue.length) {
        this._queue.push(this.queue.shift())
    }
    let swap = this.queue;
    this.queue = this._queue;
    this._queue = swap;
};

MyStack.prototype.pop = function() {
    return this.queue.shift();
};

MyStack.prototype.top = function() {
    return this.queue[0];
};

MyStack.prototype.empty = function() {
    return !this.queue.length;
};
class MyStack {
    queue1: number[] = [];
    queue2: number[] = [];
    push(x: number): void {
        this.queue2.push(x);
        while (this.queue1.length) {
            this.queue2.push(this.queue1.shift());
        }
        this.queue1 = this.queue2;
        this.queue2 = [];
    }

    pop(): number {
        return this.queue1.shift();
    }

    top(): number {
        return this.queue1[0];
    }

    empty(): boolean {
        return this.queue1.length === 0;
    }
}