標籤: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資料結構與演算法——第三章 棧