js-資料結構-棧
阿新 • • 發佈:2020-11-05
棧:先進後出,新新增和待刪除的元素都儲存在棧頂。可以用陣列的push方法入棧,pop出棧。
class Stack { constructor () { this.items = []; } push(element){ this.items.push(element); } pop(){ return this.items.pop(); } peek(){ return this.items[this.items.length-1]; } isEmpty(){ return this.items.length == 0; } size(){ return this.items.length; } clear(){ this.items = []; } print(){ console.log(this.toString()); } toString(){ return this.items.toString(); } }
棧的實際應用:二進位制轉十進位制、十進位制轉換任意進位制(二進位制、八進位制、十六進位制);平衡圓括號、漢諾塔問題
/** * 十進位制轉二進位制 * @param num --十進位制資料 * @returns {string} 轉換後的二進位制數 */ function devideBy2(num) { let stack = new Stack(); let rem; let binaryStr=''; while(num>0){ rem = num%2; stack.push(rem); num = Math.floor(num/2); } while (!stack.isEmpty()){ binaryStr +=stack.pop().toString(); } return binaryStr; } /** * 十進位制轉換為任意進位制 * @param num * @param base * @returns {string} */ function baseConvert(num,base) { let stack = new Stack(); let rem; let baseStr=''; let digit='0123456789ABCDEF'; //十六進位制會轉換 while(num>0){ rem = num%base; stack.push(rem); num = Math.floor(num/base); } while (!stack.isEmpty()){ baseStr +=digit[stack.pop()]; } return baseStr; }
檢查括號是否匹配:左括號入棧,當檢測到右括號時,進行出棧,看出棧的左括號與右括號是否可以配對,以此類推,直到棧為空。
/** * 括號配對 * @param str 包含括號的字串 * @returns {boolean|*} 配對成功返回true,失敗返回false */ function checkSymbol(str) { let openers = '([{', closers = ')]}', balanced = true, index = 0, tmp, stack = new Stack(), arr = str.split(''); while (balanced && index < arr.length) { if (openers.indexOf(arr[index]) !== -1) { stack.push(arr[index]); //左括號入棧 } else { if (stack.isEmpty()) { balanced = false; } else { tmp = stack.pop(); if (openers.indexOf(tmp) !== closers.indexOf(arr[index])) { balanced = false; } } } index++; } return (balanced && stack.isEmpty()); }