文章目录
- 一、初始栈结构
- 1.1 特性
- 1.2 注意事项
- 二、栈结构的封装
- 2.1 封装简单栈结构
- 2.2 利用栈将十进制转二进制
一、初始栈结构
1.1 特性
类似于汉诺塔,后进先出
,每次只能操作栈顶的元素。关键词:压栈
、退栈
简单示意图:
1.2 注意事项
进行递归时需要设置终止条件,否则一直往栈里面压入东西,就会造成栈溢出
二、栈结构的封装
2.1 封装简单栈结构
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title></head><body><script>class Stack {// 用数组模拟栈,但是需要给数组加一下限制,用#item避免外部访问#items = [];// 压栈push(data) {this.#items.push(data);}// 弹栈pop() {return this.#items.pop();}// 查看栈顶peek() {return this.#items[this.#items.length - 1];}// 查看当前栈是否为空isEmpty() {return this.#items.length == 0;}// 查看栈大小size() {return this.#items.length;}// 清空栈clear() {this.#items = [];}// 转为字符串toString() {return this.toString().toString(",");}}let stack = new Stack();</script></body>
</html>
2.2 利用栈将十进制转二进制
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title></head><body><script>class Stack {// 私有属性,避免被外部渲染#items = [];// 压栈push(data) {this.#items.push(data);}// 弹栈pop() {return this.#items.pop();}// 查看栈顶peek() {return this.#items[this.#items.length - 1];}// 查看当前栈是否为空isEmpty() {return this.#items.length == 0;}// 查看栈大小size() {return this.#items.length;}// 清空栈clear() {this.#items = [];}// 转为字符串toString() {return this.toString().toString(",");}}let stack = new Stack();// decNumber:要将那个数进行转换。base:将该数转换为几进制的数function convert(decNumber, base) {let number = decNumber;let remStack = new Stack();let string = "";let baseString = "0123456789ABCDEF";while (number > 0) {remStack.push(number % base);number = Math.floor(number / base);}while (!remStack.isEmpty()) {string += baseString[remStack.pop()];}return string;}convert(50);</script></body>
</html>