程式碼隨想錄演算法訓練營第第十天 | 232.用棧實現佇列 、225. 用佇列實現棧

YuanYF6發表於2024-05-18

232.用棧實現佇列

題目連結/文章講解/影片講解:https://programmercarl.com/0232.用棧實現佇列.html


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() {
    if(this.stackOut.length>0){
        return this.stackOut.pop();
    }
    while(this.stackIn.length>0){
        this.stackOut.push(this.stackIn.pop());
    }
    return this.stackOut.pop();
    
};

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

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    if (this.stackOut.length ===0 && this.stackIn.length===0) {
        return true;
    }
    return 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()
 */
  1. 用佇列實現棧

可以大家慣性思維,以為還要兩個佇列來模擬棧,其實只用一個佇列就可以模擬棧了。
建議大家掌握一個佇列的方法,更簡單一些,可以先看影片講解
題目連結/文章講解/影片講解:https://programmercarl.com/0225.用佇列實現棧.html

用一個佇列實現比較簡單
var MyStack = function() {
    this.queue1 = [];
    this.queue2 = [];
};

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

/**
 * @return {number}
 */
MyStack.prototype.pop = function() {
    if (this.queue1.length===0) {
        [this.queue1, this.queue2] = [this.queue2, this.queue1];
    }
    while(this.queue1.length>1){
        this.queue2.push(this.queue1.shift());
    }
    return this.queue1.shift();
};

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

/**
 * @return {boolean}
 */
MyStack.prototype.empty = function() {
    return !(this.queue1.length || this.queue2.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()
 */

相關文章