栈的概念
- 栈是一种遵从后进先出原则的有序集合
- 添加新元素的一端称为栈顶,另一端称为栈底
- 操作栈的元素时,只能从栈顶操作(添加、移除或取值)
![](https://img-blog.csdnimg.cn/direct/b791834347d041bf8c3fe9f65b5bff4a.png)
![](https://img-blog.csdnimg.cn/direct/610728b09e62494e8c2ff5019e007f1f.png)
栈的实现
- push() 入栈方法
- pop() 出栈方法
- top() 获取栈顶值
- size() 获取栈的元素个数
- clear() 清空栈
class Stack {constructor () {// 存储栈的数据// this.data = []this.data = {}// 记录栈的数据个数(相当于数组的 length)this.count = 0}// push() 入栈方法push (item) {// 方式1:数组方法 push 添加// this.data.push(item)// 方式2:利用数组长度// this.data[this.data.length] = item// 方式3:计数方式this.data[this.count] = item// 入栈后,count 自增this.count ++}// pop() 出栈方法pop () {// 出栈的前提是栈中存在元素,应先行检测if (this.isEmpty()) {console.log('栈为空!')return}// 移除栈顶数据// 方式1:数组方法 pop 移除// return this.data.pop()// 方式2:计数方式const temp = this.data[this.count - 1]delete this.data[--this.count]return temp}// isEmpty() 检测栈是否为空isEmpty () {return this.count === 0}// top() 用于获取栈顶值top () {if (this.isEmpty()) {console.log('栈为空!')return}return this.data[this.count - 1]}// size() 获取元素个数size () {return this.count}// clear() 清空栈clear () {this.data = []this.count = 0}
}const s = new Stack()
s.push('a')
s.push('b')
s.push('c')
console.log(s)
// Stack {data: {…}, count: 3}