什麼是棧編程
棧做爲一種數據結構,是一種只能在一端進行插入和刪除操做的特殊線性表。它按照先進後出的原則存儲數據,先進入的數據被壓入棧底,最後的數據在棧頂,須要讀數據的時候從棧頂開始彈出數據。
棧有什麼做用數組
棧是很是底層的東西,在編程語言的編譯器和內存中保存變量、方法調用。
棧結構概念:入棧 、出棧、棧頂、棧底。數據結構
js實現棧結構依靠數組編程語言
方法名 操做
push 棧頂添加元素
pop 棧頂移除元素
peek 查看棧頂
isEmpty 檢查棧是否爲空
clear 移除所有元素
size 獲取棧的大小this
下面代碼實現Stack類spa
class Stack { constructor() { // 私有屬性 this._items = []; } // 棧頂添加元素 push(el) { this._items.push(el); } // 棧頂移除元素 pop(el) { return this._items.pop(el); } // 檢查棧頂 peek() { return this._items[this._items.length - 1]; } // 檢查棧是否爲空 isEmpty() { return this._items.length === 0; } // 清除棧 clear() { this._items = []; } // 查看棧的大小 size() { return this._items.length; } }
下面來個實例code
// 十進制轉二進制 function conversionbinary(number) { let stack = new Stack(); let remainder; let binary = ''; // 進棧 while (number > 0) { remainder = number % 2; stack.push(remainder); number = Math.floor(number / 2); } // 出棧 while (!stack.isEmpty()) { binary += stack.pop(); } return binary; }
你們可能想實現一個十進制轉二進制還有其餘方法,沒必要要這麼複雜。
不知道你們有沒有想過,即便使用其餘方法實現十進制轉二進制,其思想也是棧的思想。隊列
此章完結,下一章隊列ip
歡迎你們關注,以便第一時間看到更新的文章內存