文章目录
数据结构
栈和队列类似,不过它是先入后出。
有四个常用操作:
- 入栈
- 出栈
- 堆栈溢出,Stack Overflow
- 是否空栈
数组实现
有一个指针:栈顶索引。
class ArrayStack {
constructor(size) {
this.arr = new Array(size)
this.index = -1
}
add(obj) {
if (this.isFull()) {
console.error("满啦")
return
}
this.arr[++this.index] = obj
}
remove() {
if (this.isEmpty()) {
console.error("空啦")
return
}
let temp = this.arr[this.index]
this.arr[this.index--] = null
return temp
}
isFull() {
return this.index === this.arr.length - 1
}
isEmpty() {
return this.index === -1
}
}
测试:入12345。
出543。
堆栈溢出。