代碼隨想錄訓(xùn)練營Day10|232.用棧實現(xiàn)隊列,225.用隊列實現(xiàn)棧

232. 用棧實現(xiàn)隊列

解題思路
  • 使用兩個數(shù)組的棧方法 pushpop實現(xiàn)隊列,分別定義為輸入棧和輸出棧。
  • 輸出棧主要用來彈出元素的時候,逆轉(zhuǎn)輸入棧元素的順序,然后彈出,來實現(xiàn)隊列的先入先出特點。
  • 注意彈出元素時,如果輸出棧為空,需要將輸入棧全部的元素加入到輸出棧中。

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. 用隊列實現(xiàn)棧

解題思路
  • 利用隊列模擬棧的行為,比如存在隊列 [1,2,3,4],那么作為棧彈出時,應(yīng)該優(yōu)先彈出 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()
 */
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容