溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

使用JavaScript怎么實現一個棧的數據結構

發布時間:2021-04-09 18:08:20 來源:億速云 閱讀:198 作者:Leah 欄目:web開發

今天就跟大家聊聊有關使用JavaScript怎么實現一個棧的數據結構,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。

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

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

實現一個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怎么實現一個棧的數據結構有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女