栈:
只能在顶部进行增删的列表,满足“先进后出”原则,即只能在列表顶部添加新元素,也只能从列表顶部删除新元素,如果要删除中间的元素,必须将其上面的元素挪出来;
由此可知,在实现代码部分,顶部元素很重要,故设置top值表示顶部元素的位置。
提一句题外话,在js中,基本类型的值以及特殊值(null)、引用值的指针均被分派在栈内存中,且是线程分配的。
function stack(){
this.data=[];
this.top=0;
this.push=push;
this.pop=pop;
this.gettop=gettop;//获得最顶部的元素;
this.res=undefined;//存储pop删除的值
}
function push(ele){
this.data[this.top++]=ele;
}
function pop(){
this.res=this.data.splice(--this.top,1);
return this.data;
}
function gettop(){
console.log(this.data[this.top-1])
return this.data[this.top-1]
}
var arr=new stack();
arr.push("a");
arr.push("b");
arr.push("