国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > JS > 正文

利用JavaScript實現棧的數據結構示例代碼

2024-05-06 16:38:47
字體:
來源:轉載
供稿:網友

前言

本文主要給大家介紹的是關于JavaScript實現棧的數據結構的相關內容,分享出來供大家參考學習,話不多少,來一起看看詳細的介紹:

堆棧(英語:stack),也可直接稱棧,在計算機科學中,是一種特殊的串列形式的數據結構,它的特殊之處在于只能允許在鏈接串列或陣列的一端(稱為堆疊頂端指標,英語:top)進行加入數據(push)和輸出數據(pop)的運算。另外棧也可以用一維數組或連結串列的形式來完成。 

由于堆疊數據結構只允許在一端進行操作,因而按照后進先出(LIFO, Last In First Out)的原理運作。 – 維基百科

上面是維基百科對棧的解讀。下面我們用JavaScript(ES6)代碼對棧的數據結構進行實現

實現一個Stack類

/*** Stack 類*/class Stack { constructor() { this.data = []; // 對數據初始化 this.top = 0; // 初始化棧頂位置 } // 入棧方法 push() { const args = [...arguments]; args.forEach(arg => this.data[this.top++] = arg); return this.top; } // 出棧方法 pop() { if (this.top === 0) throw new Error('The stack is already empty!'); const peek = this.data[--this.top]; this.data = this.data.slice(0, -1); return peek; } // 返回棧頂元素 peek() { return this.data[this.top - 1]; } // 返回棧內元素個數 length() { return this.top; } // 清除棧內所有元素 clear() { this.top = 0; return this.data = []; } // 判斷棧是否為空 isEmpty() { return this.top === 0; }}// 實例化const stack = new Stack();stack.push(1);stack.push(2, 3);console.log(stack.data); // [1, 2, 3]console.log(stack.peek()); // 3console.log(stack.pop()); // 3, now data is [1, 2]stack.push(3);console.log(stack.length()); // 3stack.clear(); // now data is []

用棧的思想將數字轉換為二進制和八進制

/** * 將數字轉換為二進制和八進制 */const numConvert = (num, base) => { const stack = new Stack(); let converted = ''; while(num > 0) { stack.push(num % base); num = Math.floor(num / base); } while(stack.length() > 0) { converted += stack.pop();  } return +converted;}console.log(numConvert(10, 2)); // 1010

用棧的思想判斷給定字符串或者數字是否是回文

/** * 判斷給定字符串或者數字是否是回文 */const isPalindrome = words => { const stack = new Stack(); let wordsCopy = ''; words = words.toString(); Array.prototype.forEach.call(words, word => stack.push(word)); while(stack.length() > 0) { wordsCopy += stack.pop(); } return words === wordsCopy;}console.log(isPalindrome('1a121a1')); // trueconsole.log(isPalindrome(2121)); // false

上面就是用JavaScript對棧的數據結構的實現,有些算法可能欠妥,但是僅僅是為了演示JS對棧的實現
注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 东港市| 兴仁县| 广饶县| 普安县| 井冈山市| 祁阳县| 平谷区| 宁蒗| 菏泽市| 梓潼县| 报价| 寿光市| 开远市| 大厂| 通州区| 清远市| 上犹县| 铜陵市| 句容市| 阿荣旗| 珠海市| 太仆寺旗| 大厂| 尤溪县| 蚌埠市| 晋州市| 广丰县| 沂水县| 高雄县| 梓潼县| 岫岩| 泰安市| 略阳县| 托克逊县| 库尔勒市| 桑植县| 岚皋县| 鄂托克前旗| 和顺县| 扶绥县| 马关县|