棧是一種高效的數據結構,由於數據只能在棧頂添加或刪除,因此這樣的操做很快且很容易實現。算法
棧是一種特殊的列表,棧內的元素只能經過列表的一端訪問,這一端稱之爲棧頂。
棧被稱爲一種後入先出(LIFO,last-in-first-out)的數據結構。
因爲棧具備後入先出的特色,因此任何不在棧頂的元素都沒法訪問,咱們必須先拿掉上面的元素才能訪問其棧底的元素。
對棧的主要操做是將一個元素壓入棧和將一個元素彈出棧,入棧使用push()
方法,出棧使用pop()
方法。數組
咱們將使用JavaScript實現棧結構,各部分功能使用註釋說明。
存儲數據咱們使用的是數組。數據結構
/** * Stack 構造方法 */ function Stack () { this.dataStore = [] this.top = 0 this.push = push this.pop = pop this.peek = peek this.clear = clear this.length = length } /** * push() 該方法用於向棧壓入元素 * 向棧中壓入一個新元素,將其保存在數組中變量top所對應的位置 * 而後將 top + 1 讓其指向數組中下一個空位置 * @param {*} element */ function push (element) { this.dataStore[this.top++] = element } /** * pop() 該方法用於從棧頂推出元素 * 返回棧頂元素,同時將變量top - 1 */ function pop () { return this.dataStore[--this.top] } /** * peek() 該方法用於返回數組的第 top - 1 個位置的元素 */ function peek () { return this.dataStore[this.top - 1] } /** * length() 該方法用於獲取棧的長度 * 返回當前top值便可得到棧內元素個數 */ function length () { return this.top } /** * clear() 該方法用於清空棧 * 將top設爲0 */ function clear () { this.top = 0 }
咱們能夠利用棧將一個數字從一種數制轉換爲另外一種數制。
假設想將數字n轉換爲以b爲基數的數字,實現的算法以下:this
此算法只針對基數爲2-9的狀況
代碼實現以下:code
function mulBase (num, base) { let s = new Stack() do { s.push(num % base) num = Math.floor(num /= base) } while (num > 0) { let converted = '' while (s.length() > 0) { converted += s.pop() } return converted } }
使用棧,咱們能夠判斷一個字符串是否爲迴文。
字符串完整壓入棧內後,經過持續彈出棧中的每個字母就能夠獲得一個新的字符串,該字符串恰好與原來的字符串順序相反。咱們只須要比較兩個字符串便可。若是相等,就是一個迴文。ip
function isPalindrome (word) { let s = new Stack() for (let i = 0; i < word.length; ++i) { s.push(word[i]) } let rword = '' while (s.length() > 0) { rword += s.pop() } if (word == rword) { return true } else { return false } }
以上就是對JavaScript實現棧的介紹。element
參考資料:數據結構與算法JavaScript描述 第4章 棧