原文链接:https://note.noxussj.top/?source=helloworld
栈是基础数据结构,栈是一种遵循后进先出原则的有序集合,添加新元素的一端称为栈顶,另一端称为栈底。操作栈的元素时,只能从栈顶操作(添加、移除、取值)。

实现功能
在 JavaScript 中没有栈,但是可以通过 Array 实现栈的所有功能
- push () 入栈
- pop () 出栈
- top () 获取栈顶值
- size () 获取栈的元素个数
- clear () 清空栈
应用场景
- 十进制转二进制
- 判断字符串的括号是否有效
- 函数调用堆栈
- 二叉树前序遍历(迭代方式)
- ...
基础案例
通过数组实现
1const stack = [1] 2stack.push(2) // 入栈 3stack.pop() // 出栈 4const top = stack[0] // 获取栈顶值 5const size = stack.length // 获取栈的元素个数 6stack.length = 0 // 清空栈
通过类模拟实现
1class Stack { 2 constructor() { 3 this.data = {} 4 this.count = 0 5 } 6 7 /** 8 * 入栈 9 */ 10 push(item) { 11 this.data[this.count++] = item 12 13 return item 14 } 15 16 /** 17 * 出栈 18 */ 19 pop() { 20 if (this.count > 0) { 21 const item = this.data[this.count - 1] 22 delete this.data[--this.count] 23 24 return item 25 } else { 26 return -1 27 } 28 } 29 30 /** 31 * 获取栈顶值 32 */ 33 top() { 34 if (this.count > 0) { 35 return this.data[this.count - 1] 36 } else { 37 return -1 38 } 39 } 40 41 /** 42 * 获取栈的元素个数 43 */ 44 size() { 45 return this.count 46 } 47 48 /** 49 * 清空栈 50 */ 51 clear() { 52 this.data = {} 53 this.count = 0 54 } 55} 56 57const stack = new Stack() 58 59stack.push('a') 60stack.push('b') 61stack.push('c') 62 63stack.pop()
