學(xué)習(xí)js數(shù)據(jù)結(jié)構(gòu)與算法1—棧

棧遵從后進(jìn)先出原則

就像生活中的放盤子,后放的先拿走

棧也被用在編譯器和內(nèi)存中保存變量、方法調(diào)用等

3.1 棧的創(chuàng)建

創(chuàng)建一個(gè)類來表示棧

function Stack() {
    // 首先需要一種數(shù)據(jù)結(jié)構(gòu)來保存棧里的元素,可以選擇數(shù)組
    var items = [];
    // 接下來,要為棧聲明一些方法
    /*
        push(ele): 添加一個(gè)新元素到棧頂
        pop(): 移除棧頂元素,并返回被移除的元素
        peek(): 返回棧頂元素,不對(duì)棧進(jìn)行操作
        isEmpty(): 如果棧里沒有元素返回true,否則返回false
        clear(): 移除棧里的所有元素
        size(): 返回棧里的元素個(gè)數(shù)
    */
    
    // push方法
    this.push = function(ele) {
        items.push(ele);    
    };
    // pop方法
    this.pop = function() {
        return items.pop();  
    };
    // peek方法
    this.peek = function() {
        return items[items.length - 1];  
    };
    // isEmpty方法
    this.isEmpty = function() {
        return items.length === 0;  
    };
    // clear方法
    this.clear = function() {
        // items.length = 0;  // 保留了數(shù)組其他屬性
        items = [];     // 更高效
    };
    // size方法
    this.size = function() {
        return items.length;
    };
    
    // 最后實(shí)現(xiàn)一個(gè)輔助方法print打印棧的內(nèi)容
    this.print = function() {
        console.log(items.toString());  
    };
}

使用Stack類
    var stack = new Stack();
    console.log(stack.isEmpty());   // true
    stack.push(5);
    stack.push(8);
    console.log(stack.peek());      // 8
    stack.push(11);
    console.log(stack.size());      // 3
    console.log(stack.isEmpty());   // false
    stack.push(15);
利用棧可以實(shí)現(xiàn)二進(jìn)制轉(zhuǎn)換
    function divideBy2(decNum) {
        var remStack = new Stack(),
            rem,
            binaryStr = '';
            
        while (decNum > 0) {
            rem = Math.floor(decNum % 2);
            remStack.push(rem);
            decNum = Math.floor(decNum / 2);
        }
        
        while (!remStack.isEmpty()) {
            binaryStr += remStack.pop().toString();
        }
        
        return binaryStr;
    }
    
任意進(jìn)制的轉(zhuǎn)換
    function baseCoverter(decNum, base) {
        var remStack = new Stack(),
            rem,
            str = '',
            digits = '0123456789ABCDEF';
        
        while (decNum > 0) {
            rem = Math.floor(decNum % base);
            remStack.push(rem);
            decNum = Math.floor(decNum / 2);
        }
        
        while (!remStack.isEmplty()) {
            str += digits[remStack.pop()];
        }
        
        return str;
    }
    
    console.log(baseCoverter(100, 8));  // 144
    console.log(baseCoverter(10, 2));   // 1010
    console.log(baseCoverter(100345, 16));  // 187F9

※ 以上內(nèi)容是我在看了js數(shù)據(jù)結(jié)構(gòu)與算法的時(shí)候記錄的筆記,僅僅是為了方便查看,哈哈,有需要的小伙伴也可以拿來參考,不用買書了

最后編輯于
?著作權(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)容