棧是一種特殊的列表旨别,一種后進(jìn)先出的數(shù)據(jù)結(jié)構(gòu)。任何不在棧頂?shù)脑囟紵o法訪問汗茄。為了得到棧底的元素秸弛,必須拿先拿掉上面的元素。所以就有了入棧和出棧洪碳。
此例递览,利用了數(shù)組來充當(dāng)數(shù)據(jù)倉庫,入棧使用push()方法瞳腌,出棧使用pop()方法绞铃。
* 使用var stack = new Stack() 創(chuàng)建一個(gè)棧實(shí)例
* 實(shí)例屬性
* this.dataStore 初始化空數(shù)組,數(shù)據(jù)倉庫
* this.top 記錄棧頂?shù)奈恢? * 實(shí)例方法
* push(ele) 棧頂添加一個(gè)元素
* pop() 彈出棧頂元素
* peek() 返回當(dāng)前棧頂元素(top值不會(huì)修改嫂侍,僅查看)
* length() 返回當(dāng)前元素個(gè)數(shù)
* clear() 清空棧
具體實(shí)現(xiàn)方法
function Stack() {
this.dataStore = []; //初始化空數(shù)組保存
this.top = 0; //記錄棧頂位置
};
/*
*push()棧頂添加一個(gè)數(shù)據(jù)
*param{ele} 添加的元素
*/
Stack.prototype.push = function(ele) {
this.dataStore[this.top++] = ele;
};
//移除棧頂元素top值會(huì)修改
Stack.prototype.pop = function() {
let _pop = this.dataStore.pop();
this.top--;
return _pop
};
//返回棧頂元素但是top值不做修改
Stack.prototype.peek = function() {
return this.dataStore[this.top - 1]
};
//返回當(dāng)前棧存儲(chǔ)的元素個(gè)數(shù)
Stack.prototype.length = function() {
return this.top
}
//清空棧
Stack.prototype.clear = function() {
this.dataStore = [];
this.top = 0;
}
使用舉例
要計(jì)算一個(gè)階乘5儿捧!
function fact(n) {
if(n === 0){
return 1;
} else {
return n * fact(n-1)
}
}
利用棧的方式,將數(shù)字推入棧挑宠,然后一個(gè)一個(gè)取出
function fact(n) {
var stack = new Stack();
while (n > 1) {
stack.push(n--)
}
var product = 1;
while (stack.length() > 0) {
product *= stack.pop();
}
return product;
}