js描述栈及栈的使用
- 栈的特性就是只能通过一端访问,这一段就是叫做栈顶。咖啡馆内的一摞盘子就是最形象的栈的例子;
- 根据栈的特性,就可以定义栈的一些特殊属性和方法;用js的描述栈的时候底层数据结构用的是数组,通过this.top来跟踪最后一个元素的索引来实现栈的数据结构;
function Stack(){
this.dataSource=[];
this.top=0;
this.push=push;
this.pop=pop;
this.peek=peek;
this.clear=clear;
this.length=length;
}
function push (element){
this.dataSource[this.top++]=element;
}
function pop(){
return this.dataSource[--this.top];
}
function peek(){
return this.dataSource[this.top-1];
}
function clear(){
this.dataSource=[];
this.top=0;
}
function length(){
return this.top;
}
栈的使用场景
- 回文:即一个字符串的正序和反序 。例如hello的反序是olleh;
//回文实例
function isPalindRome(word){
var w=new Stack();
for(var i=0;i<word.length;i++){
w.push([word[i]]);
}
console.log(w.dataSource);//hello
var rword='';
while (w.length()>0){
rword+= w.pop();
}
console.log(rword); //olleh
}
var str='hello';
递归
//递归实现5的阶乘
function fact(n){
var e=new Stack();
while (n>=1){
e.push(n--);
}
console.log(e.dataSource);
var product=1;
while (e.length()>0){
product=product* e.pop();
}
console.log(product);
}
fact(10)