栈结构遵循以下规则
- 数据从栈顶 (又称为栈尾) 进入
- 从栈顶退出
- 遵循后进先出的 LIFO 原则
一个栈应该有以下方法: push pop peek isEmpty size clear toString
封装一个栈
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
class Stack { private stack: unknown[] = [];
push(data: unknown) { this.stack.push(data); } pop() { return this.stack.pop(); }
peek() { return this.stack[this.stack.length - 1]; }
isEmpty() { return this.stack.length === 0; } size() { return this.stack.length; } clear() { this.stack = []; } toString() { return this.stack.join("-"); } }
const stack = new Stack();
debugger;
|
应用: 进制转换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import { Stack } from "./stack";
function convert(DecNumber: number, base: number) { const remStack = new Stack(); const baseString = "0123456789ABCDEF"; let res = ""; while (DecNumber > 0) { remStack.push(DecNumber % base); DecNumber = Math.floor(DecNumber / base); } while (!remStack.isEmpty()) { res += baseString[remStack.pop() as number]; } return res; }
console.log(convert(1234, 16));
|