JavaScript資料結構與演算法——第三章 棧

來源:互聯網
上載者:User

標籤:git   asc   style   數組   資料結構   size   his   pre   資料   

棧:後進先出。棧頂在最後,棧底在最前。新添加的元素和待刪除的元素抖儲存在棧的末尾。

建立一個棧:

function Stack() {    var items = []; /*用數組儲存棧裡的元素*/    this.push = function(e) {        items.push(e);    }    this.pop = function() {        return items.pop();    }    this.peek = function() {        return items[length - 1];    }    this.isEmpty = function() {        return items.length == 0;    }    this.size = function() {        return items.length;    }    this.clear = function() {        items = [];    }    this.print = function() {        console.log(items.toString());    }}

使用stack類,執行個體化一個棧:

var stack= new Stack();/*建立一個空棧*//*使用它的方法*/stack.size();  //0stack.isEmpty();  //truestack.push(2);stack.push(3);stack.print(); //"2,3"

用棧做什嗎?

例子:10進位轉化成指定的進位數數。

function baseConverter(decNumber,base){    var stack=new Stack();    var rem,        binaryString=‘‘,        digits=‘0123456789ABCDEF‘;    while(decNumber>0){        rem=decNumber%base;        stack.push(rem);        decNumber=Math.floor(decNumber/base);    }    while(!stack.isEmpty()){         binaryString+=digits[stack.pop()];    }    return binaryString;}

 

JavaScript資料結構與演算法——第三章 棧

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.