js中实现Stack栈类

栈(stack)又名堆栈,是一种类似列表的数据结构,栈内的元素只能从列表的一端进行访问,这一端成为栈顶,另一端称为栈底;栈遵循先进后出的原则,只允许在栈顶进行操作。

将元素添加进栈中被成为入栈(压栈)的方法push

将当前栈顶元素删除称为出栈的方法 pop

查看当前栈顶元素的方法 peek

查看当前栈的长度方法 size

删除栈的方法 clear

栈中的属性是top用来记录当前栈顶的位置

用代码实现:

function Stack(){
    this.itemArr=[];
    this.top=0;//初始化栈顶位置为0
}

Stack.prototype={
    push:function(el){
        return this.itemArr[this.top++]=el;
    },
    pop:function(){
        return this.itemArr.splice(--this.top,1)
    },
    peek:function(){
        return this.itemArr[this.top-1];
    },
    size:function(){
        return this.top;
    },
    clear:function(){
        this.top=0;
        this.itemArr=[];
        return this.itemArr;
    }
}
var arr=new Stack();
原文地址:https://www.cnblogs.com/shanchui/p/14048904.html