美文网首页
代码随想录训练营Day10|232.用栈实现队列,225.用队列

代码随想录训练营Day10|232.用栈实现队列,225.用队列

作者: 是小张啊啊 | 来源:发表于2023-10-20 20:50 被阅读0次

232. 用栈实现队列

解题思路
  • 使用两个数组的栈方法 pushpop实现队列,分别定义为输入栈和输出栈。
  • 输出栈主要用来弹出元素的时候,逆转输入栈元素的顺序,然后弹出,来实现队列的先入先出特点。
  • 注意弹出元素时,如果输出栈为空,需要将输入栈全部的元素加入到输出栈中。

var MyQueue = function() {
    this.stackIn = []; // 输入栈
    this.stackOut = []; // 输出栈
};

/** 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
    this.stackIn.push(x);
};

/**
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    let size = this.stackOut.length;
    if (size) {
        return this.stackOut.pop()
    }
    while (this.stackIn.length) {
        this.stackOut.push(this.stackIn.pop())
    }
    return this.stackOut.pop()
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    const x = this.pop()
    this.stackOut.push(x);
    return x;
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    return !(this.stackIn.length || this.stackOut.length)
};

225. 用队列实现栈

解题思路
  • 利用队列模拟栈的行为,比如存在队列 [1,2,3,4],那么作为栈弹出时,应该优先弹出 4
  • 除去最后一个元素,将剩余 0 ~ (length - 1)的元素依次加入至末尾,即可。
var MyStack = function() {
    this.queue = []
};

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

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

/**
 * @return {number}
 */
MyStack.prototype.top = function() {
    let x = this.pop()
    this.queue.push(x)
    return x
};

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

/**
 * 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()
 */

相关文章

网友评论

      本文标题:代码随想录训练营Day10|232.用栈实现队列,225.用队列

      本文链接:https://www.haomeiwen.com/subject/hlokidtx.html