栈是一种受限的线性表,也可以看作是递归的一种实现结构。后进先出(LIFO)。其限制只能在栈的一端对栈进行插入,删除。这一端称为
栈顶
,而末端称为栈底
。
function Stack() {
this.items = [];
// 压栈
Stack.prototype.push = function(element) {
this.items.push(element);
};
// 从栈中取出
Stack.prototype.pop = function() {
return this.items.pop();
};
// 查看栈顶元素
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;
};
// toString方法
Stack.prototype.toString = function() {
var resultStr = "";
for (let i = 0; i < this.items.length; i++) {
resultStr += i;
}
return resultStr;
};
}
const list = new Stack();