代码实现
顺序存储(数组)
JS代码实现
ES5代码实现
function Stack(){
this.stack = [];
}
// 添加元素到栈顶
Stack.prototype.push = function(ele){
this.stack.push(ele);
}
// 移除栈顶的元素
Stack.prototype.pop = function(){
this.stack.pop();
}
// 查看栈顶的元素
Stack.prototype.peek = function(){
return this.stack[this.stack.length-1];
}
// 查看栈是否为空
Stack.prototype.isEmpty = function(){
return this.stack.length == 0;
}
// 移除栈里的所有元素
Stack.prototype.clear = function(){
this.stack = [];
}
// 返回栈里的元素个数
Stack.prototype.size = function(){
return this.stack.length;
}