栈结构
是一种受限的线性结构,
只能在栈顶添加/删除元素。
后进先出 LIFO
例如:自助餐的托盘,实体邮件。
函数调用栈
A调用B,B调用C,C调用D。
A被放在了栈底,B在A的上边,C在B的上边,D在栈顶
D被执行完后会先弹出栈
递归:连续不断调用自己;容易出现栈溢出
654321顺序进栈
不合法的出栈顺序是:C
A.543612 B.45321 C.346521 D.234156
实现基于数组的栈
//封装基于数组的栈
function Stack(){
this.items=[];
// 1入栈 push
Stack.prototype.push=function(Element){
this.items.push(Element);
}
//2.出栈 pop
Stack.prototype.pop=function(){
this.items.pop();
}
// 3.查看栈顶 peek
Stack.prototype.peek=function(){
return this.items[this.items.length-1];
}
// 判空
Stack.prototype.isEmpty=function(){
return this.items.length==0;
}
//返回元素个数 size
Stack.prototype.size=function(){
return this.items.length;
}
//toString
Stack.prototype.toString=function(){
var resultString="";
for(var i=0;i<this.items.length;i++){
resultString+=this.items[i]+" ";
}
return resultString;
}
}
var s= new Stack();
// 入栈
s.push(110);
s.push(120);
s.push(130);
s.push(140);//110 120 130 140
// 出栈
s.pop();//110 120 130
// 查看栈顶
console.log(s.peek());
// 判空
console.log(s.isEmpty());
// 返回元素个数
console.log(s.size());
// 输出数组大的toString
console.log(s.toString());
255

被折叠的 条评论
为什么被折叠?



