我们需要实现以下功能:
push() 入栈方法
pop() 出栈方法
top() 获取栈顶值
size() 获取栈的元素个数
clear() 清空栈
class Stack {
constructor () {
// 存储栈的数据
this.data = []
// 记录数据的个数
this.count = 0
}
// 入栈方法
push (item) {
// this.data.push(item)
// this.data[this.data.length] = item
this.data[this.count] = item
this.count++
}
// 出栈方法
pop () {
if (this.isEmpty()) {
console.log('栈为空')
return
}
const temp = this.data[this.count - 1]
delete this.data[--this.count]
return temp
}
// 检测栈是否为空
isEmpty () {
return this.count === 0
}
// 获取栈顶元素
top () {
if (this.isEmpty()) {
console.log('栈为空')
return
}
return this.data[this.count - 1]
}
// 获取元素个数
size () {
return this.count
}
// 清空栈
clear () {
this.data = []
this.count = 0
}
}
1