前言
本文主要給大家介紹的是關於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()); // 3
console.log(stack.pop()); // 3, now data is [1, 2]
stack.push(3);
console.log(stack.length()); // 3
stack.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')); // true
console.log(isPalindrome(2121)); // false
上面就是用JavaScript對棧的數據結構的實現,有些算法可能欠妥,但是僅僅是為了演示JS對棧的實現😄
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對的支持。