栈的数据结构特点
#特点:后进先出
1.push 入栈
2.pop 将栈顶的数据出栈
3.peek 获取栈顶的数据
4.isEmpty 判断栈是否为空
5.size 返回栈的长度
/**
* 入栈 push
* 出栈 pop
* peek 获取栈顶
* isEmpty 判断栈是否为空
* size 可以看栈里有多少个
*/
function Stack() {
this.items = [];
}
Stack.prototype.push = function (val) {
this.items.push(val);
}
Stack.prototype.pop = function () {
var res = this.items.pop();
return res;
}
Stack.prototype.peek = function () {
return this.items[this.items.length - 1];
}
Stack.prototype.isEmpty = function () {
return this.items.length == 0;
}
Stack.prototype.size = function () {
return this.items.length;
}
var arr = new Stack();
arr.push(2)
arr.push(4)
console.log(arr);
arr.pop()
console.log(arr);
console.log(arr.peek()); // 2
console.log(arr.isEmpty()); //false
console.log(arr.size()); //1