一种先入后出、后入先出的数据结构
这里考虑数组的复杂度,使用对象方式来模拟
export class Stack {
private count: number;
private obj: object;
constructor() {
this.count = 0;
this.obj = {};
}
// 向栈内追加
push(param) {
this.obj[this.count] = param;
this.count++;
}
// 推出栈数据
pop() {
const res = this.obj[this.count - 1];
delete this.obj[this.count - 1];
this.count--; // 移除之后数据量减少
return res; // 将被移出栈的数据返回
}
isEmpty() {
return this.count === 0;
}
size() {
return this.count;
}
}
应用场景: 进制转换
export function decimalConversion(value: number, decimal: number) {
// 实例化栈
const stack = new Stack();
// 准备进制所需的源数据
const resource = "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ";
// 对传入的数据进行保存,方便操作
let num: number = value;
let res: number = 0;
let resStr: string = "";
// 判断是否符合进制的要求
if (!(decimal >= 2 && decimal <= 36)) {
// 进制只有2~36,如果不是这种情况则返回
return "请输入2~36位的进制";
}
// 只要num大于0 就继续
while (num > 0) {
res = Math.floor(num % decimal); // 拿到num对decimal的取余的整数部分
stack.push(res); // 将结果推入到栈中
num = Math.floor(num / decimal);
}
// 将栈中的值取出来
while (!stack.isEmpty()) {
const index = stack.pop();
resStr += resource[index];
}
return resStr;
}