代码随想录算法训练营第十天 | 232.用栈实现队列、225.用队列实现栈

56 阅读1分钟

232.用栈实现队列

225.用队列实现栈

232. 用栈实现队列

  • 我的思路:stk1为缓冲区,stk2为队列区
  • 注意点:实现stk1的元素传递到stk2时,不可用以长度为条件的for循环,因为每次pop数组长度都在变!

var MyQueue = function() {
    this.stk1 = [];
    this.stk2 = [];
};

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

/**
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    if (this.stk2.length === 0) {
        while (this.stk1.length > 0) {
            this.stk2.push(this.stk1.pop());
        }
    }
    const n2 = this.stk2.pop();
    return n2;
};

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

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    if (this.stk1.length + this.stk2.length === 0)  return true;
    return false;
};

225. 用队列实现栈

  • 感想:用队列shift调整位置实现pop好巧妙啊!

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

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

/**
 * @return {number}
 */
MyStack.prototype.pop = function() {
    // 法1: 备份 
    // const n = this.q[this.q.length - 1];
    // const q2 = [];
    // while (this.q.length > 1) {
    //     q2.push(this.q.shift());
    // }
    // this.q = q2.slice();
    
    // 法2: 循环调整位置
    let len = this.q.length;
    len--;
    while (len--) {
        this.q.push(this.q.shift());
    }
    return this.q.shift();
};

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

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