棧(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();