棧(stack)又名堆棧,它是一種運算受限的線性表javascript
定義:棧是限定僅在表頭進行插入和刪除操做的線性表。要搞清楚這個概念,首先要明白」棧「原來的意思,如此才能把握本質。"棧「者,存儲貨物或供旅客住宿的地方,可引伸爲倉庫、中轉站,因此引入到計算機領域裏,就是指數據暫時存儲的地方,因此纔有進棧、出棧的說法。java
好比咱們在洗盤子時,一碟盤子能夠想象成一個棧,只能從最上面取盤子,盤子洗淨後,放在另外一個地方也只能摞在盤子的最上面。這種後入先出(LIFO,last-in-first-out)的數據結構被稱爲棧。數組
實現一個棧,就得決定存儲數據的底層數據結構,這裏採用數組。數據結構
// 實現Stack類的構造函數
function Stack () {
this.dataStore = [] // 保存棧內元素
this.top = 0 // 記錄棧頂位置
}
Stack.prototype = {
constructor: Stack,
push: function (element) {
this.dataStore[this.top] = element
this.top++
},
pop: function () {
return this.dataStore[--this.top]
},
peek: function () {
return this.dataStore[this.top - 1]
},
length: function () {
return this.top
},
clear: function () {
this.top = 0
}
}
複製代碼
一個單詞,短語或數字,從前日後寫和從後往前寫都是同樣的,就是迴文。函數
將拿到的字符串的每一個字符按照從左到右的順序壓入棧,當字符串中的字符都入棧後,棧內就保存了一個反轉後的字符串,判斷兩個字符串是否相等便可。this
function isPalindrome (word) {
var s = new Stack()
for (var i = 0; i < word.length; i++) {
s.push(word[i])
}
var rword = ''
while (s.length() > 0) {
rword += s.pop()
}
if (word === rword) {
return true
} else {
return false
}
}
複製代碼
用棧模擬實現遞歸spa
首先將數字從5到1壓入棧,而後使用一個循環,將數字挨個彈出連乘。prototype
// 5! = 5 * 4 * 3 * 2 * 1
function fact(n) {
var s = new Stack()
while (n > 1) {
s.push(n--)
}
var product = 1
while (s.length() > 0) {
product *= s.pop()
}
return product
}
複製代碼