Leetcode刷题(第225题)——用队列实现栈

x33g5p2x  于2022-03-17 转载在 其他  
字(1.1k)|赞(0)|评价(0)|浏览(181)

一、题目

二、示例

输入:
["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

三、思路
本题主要考察栈和队列的特性,首先第一种思路是采用双队列来解决,但是这样存在一个问题,就是空间复杂度过高,此时我们可以使用单个队列来解决问题,解决方法就是使用一个变量记录当前队列的长度,然后队列从前面删除,再从后面加入。
四、代码展示

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

/** 
 * @param {number} x
 * @return {void}
 */
MyStack.prototype.push = function (x) {
    this.queue.push(x)
    this.length++
};

/**
 * @return {number}
 */
MyStack.prototype.pop = function () {
    let curLength = this.length
    while(this.length > 1) {
        this.queue.push(this.queue.shift())
        this.length--
    }
    this.length = curLength - 1
    return this.queue.shift()
};

/**
 * @return {number}
 */
MyStack.prototype.top = function () {
    return this.queue[this.length - 1]
};

/**
 * @return {boolean}
 */
MyStack.prototype.empty = function () {
    return this.length > 0 ? false : true
};

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

五、总结

相关文章

微信公众号

最新文章

更多