LeetCode第225题:用队列实现栈

题干

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

实现 MyStack 类:

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

注意:

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

来源:力扣(LeetCode)
链接:leetcode-cn.com/problems/im…
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法:双队列

如何使用队列实现栈呢,我这里简述以下实现过程:

我们知道栈这种数据结构是先进后出,而队列这种数据结构是先进先出的。所以我们设置两个队列,保证其中一个队列总是为空。并且我们添加数据时总是像空的队列里面添加,接着再按照队列的规则将不为空的队列的所有值加入当前的队列中。

所以只有push比较特殊而已。

接下来我们看一下代码实现:

/**
 * Initialize your data structure here.
 */
var MyStack = function () {
    this.queue1 = []
    this.queue2 = []
};

/**
 * Push element x onto stack. 
 * @param {number} x
 * @return {void}
 */
MyStack.prototype.push = function (x) {
    if (this.queue2.length == 0) {
        this.queue2.push(x)
        for (let i = 0; i < this.queue1.length;) {
            let a = this.queue1.pop();
            console.log(a,'aaaa')
            this.queue2.unshift(a)

        }
    } else if (this.queue1.length == 0) {
        this.queue1.push(x)
        for (let i = 0; i < this.queue2.length;) {
            let a = this.queue2.pop();
            console.log(a, 'bbbb')
            this.queue1.unshift(a)
        }
    }
}

/**
 * Removes the element on top of the stack and returns that element.
 * @return {number}
 */

MyStack.prototype.pop = function () {
    if (this.queue2.length == 0) {
        return this.queue1.pop()
    } else {
        return this.queue2.pop()
    }
}

/**
 * Get the top element.
 * @return {number}
 */
MyStack.prototype.top = function () {
    return this.queue1.length == 0 ? this.queue2[this.queue2.length - 1] : this.queue1[this.queue1.length - 1]
};

/**
 * Returns whether the stack is empty.
 * @return {boolean}
 */
MyStack.prototype.empty = function () {
    if (this.queue2.length == 0 && this.queue1.length == 0) {
        return true
    }
    return false
};

/**
 * 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()
 */
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享