利用数组封装栈结构(后进先出)
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 () {
let resultString = ''
for(let i = 0; i < this.items.length; i++) {
resultString += this.items[i] + ''
}
return resultString
}
}