<<劍指offer>>--javascript(5)-用兩個棧實現(xiàn)隊列

用兩個棧實現(xiàn)隊列

題目描述

用兩個棧來實現(xiàn)一個隊列,完成隊列的Push和Pop操作。 隊列中的元素為int類型。
代碼如下:

function Stack(){
    var item = [];
    this.push = function(node){
        item.push(node);
    };
    this.pop = function(){
        return item.pop();
    };
    this.isEmpty = function(){
        return item.length === 0;
    };
}
var stack1 = new Stack();
var stack2 = new Stack();
function push(node)
{
    stack1.push(node);
    // write code here
}
function pop()
{
    if(stack1.isEmpty() && stack2.isEmpty()){
         throw new Error("Queue is empty");
    }
    if(stack2.isEmpty()){
        while(!stack1.isEmpty()){
            stack2.push(stack1.pop());
        }
    }
    return stack2.pop();
    // write code here
}
module.exports = {
    push : push,
    pop : pop
};

解題思路

是一種后進先出的數(shù)據(jù)結(jié)構(gòu),而隊列是一種先進先出的數(shù)據(jù)結(jié)構(gòu),那么本題中,
1、實現(xiàn)入隊:將元素直接壓入棧1。
2、實現(xiàn)出隊:先判斷兩個棧是否都為空,如果不是,在判斷棧2,如果為空,棧1不為空,先將棧1的元素全部出棧,按順序壓入棧2,然后再從棧2中出棧,就取得了原來在棧1棧底的元素了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

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

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