最基本是数据结构,没什么难的;
实现了push、pop、peek(查看栈顶元素)、isEmpty、size、toString等方法;
function Stack() {
// 栈中的属性
this.items = [];
// 栈相关的操作
// 1.将元素压入栈
Stack.prototype.push = function (element) {
this.items.push(element);
};
// 2.从栈中取出元素
Stack.prototype.pop = function () {
return this.items.pop();
};
// 3.查看栈顶元素
Stack.prototype.peek = function () {
return this.items[this.items.length - 1];
};
// 4.判断栈是否为空
Stack.prototype.isEmpty = function () {
return this.items.length == 0;
};
// 5.获取栈中元素的个数
Stack.prototype.size = function () {
return this.items.length;
};
// 6.实现tostring
Stack.prototype.toString = function () {
var resultString = "";
for (let i = 0; i < this.items.length; i++) {
resultString += this.items[i] + " ";
}
return resultString;
};
}