LeetCode第232题:用栈实现队列

题干:

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):

实现 MyQueue 类:

  • void push(int x) 将元素 x 推到队列的末尾
  • int pop() 从队列的开头移除并返回元素
  • int peek() 返回队列开头的元素
  • boolean empty() 如果队列为空,返回 true ;否则,返回 false

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

解法:

废话不多说,队列是先进先出,栈是先进后出,刚进来的元素就在栈顶,我们可以使用这一特性定义两个栈s1,s2,在每次push时,先将s2清空,再将数据push到s1上,再将s1依次压栈到s2上,这就实现了栈底元素到队列头。

接着当我们pop队列头时,我们将s2的栈顶删除,这就相当于我们删除了s2队列的首部。但是同时我们还要将s1清空,因为我们需要两个栈保持同步,再将s2依次压栈到s1,这样我们保持了 s1的不变性。

代码实现:

/**
 * Initialize your data structure here.
 */
var MyQueue = function () {
    this.stack1 = [];
    this.stack2 = [];
};

/**
 * Push element x to the back of queue. 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function (x) {
    this.stack2 = []
    this.stack1.push(x);
    for (let i = this.stack1.length - 1; i >= 0; i--) {
        this.stack2.push(this.stack1[i])
    }
};

/**
 * Removes the element from in front of queue and returns that element.
 * @return {number}
 */
MyQueue.prototype.pop = function () {
    let pop=this.stack2.pop();
    this.stack1=[]
    for (let i = this.stack2.length - 1; i >= 0; i--) {
        this.stack1.push(this.stack2[i])
    }
    console.log(this.stack1)
    return pop;
};

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function () {
    return this.stack2[this.stack2.length - 1]
};

/**
 * Returns whether the queue is empty.
 * @return {boolean}
 */
MyQueue.prototype.empty = function () {
    return this.stack2.length == 0 ? true : false
};

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