【JavaScript實(shí)現(xiàn)數(shù)據(jù)結(jié)構(gòu)系列】棧

堆??梢杂面湵砗蛿?shù)組兩種方式實(shí)現(xiàn),這里分別給出這兩種實(shí)現(xiàn)方式。
代碼如下:

//數(shù)組實(shí)現(xiàn)
function Stack(){
   this.items = [];
   this.size = 0;
}
Stack.prototype = {
   constructor:Stack,
   push:function(data){
       this.items[this.size++] = data;
   },
   pop:function(){
       return this.items[--this.size];
   },
   clear:function(){
       this.size = 0;
       this.items = [];
   },
   perk:function(){
       return this.items[this.size-1];
   }
}
//鏈表實(shí)現(xiàn)
    function Stack(){
        this.top = null;
        this.size = 0;
    }
    Stack.prototype = {
        constructor:Stack,
        push:function(data){
            var node = {
                data:data,
                next:null
            };
            node.next = this.top;
            this.top = node;
            this.size++;
        },
        pop:function(){
            if(this.top === null){
                return null;
            }
            var out = this.top;
            this.top = this.top.next;
            if(this.size > 0){
                this.size--;    
            }
            return out.data;
        },
        perk:function(){
            return this.top === null ? null:this.top.data; 
        },
        clear:function(){
            this.top = null;
            this.size = 0;
        }

測(cè)試:

var stack = new Stack();
stack.push('k');
stack.push('b');
console.log(stack.perk());//輸出b
stack.pop();
console.log(stack.perk());//輸出k

棧的應(yīng)用

例子:數(shù)值進(jìn)制轉(zhuǎn)換
算法思想如下:
(1) 最高位為 n % b,將此位壓入棧。
(2) 使用 n/b 代替 n。
(3) 重復(fù)步驟 1 和 2,直到 n 等于 0,且沒有余數(shù)。
(4) 持續(xù)將棧內(nèi)元素彈出,直到棧為空,依次將這些元素排列,就得到轉(zhuǎn)換后數(shù)字的字符串形式。

具體代碼實(shí)現(xiàn):

function mulBase(num,base){
    var stack = new Stack();
    do{
        stack.push(num % base); 
        num = Math.floor(num / base);
    }while(num>0);
    var result = '';
    while(stack.size > 0){
        result += stack.pop();
    }
    return result;
}
console.log(mulBase(234,2)); //輸出11101010

初學(xué)者學(xué)習(xí)筆記,如有不對(duì),還希望高手指點(diǎn)。如有造成誤解,還希望多多諒解。

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

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

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