一、定义
栈遵循LIFO-(Last in, First out)原则即先进后出,栈存储结构被用在编程语言的编译器和内存中保存变量、方法调用(js的执行栈)等,也被用于浏览器历史记录存储(浏览器回退操作)。
二、JavaScript模拟实现
class Stack {
constructor() {
this.count = 0;
this.items = {};
}
push(val) {
this.items[this.count] = val;
this.count++;
}
size() {
return this.count;
}
isEmpty() {
return this.count === 0;
}
// 弹出栈顶元素
pop() {
if (this.isEmpty()) return undefined;
this.count--;
const result = this.items[this.count];
delete this.items[this.count];
return result;
}
peek() {
if (this.isEmpty()) return undefined;
return this.items[this.count--];
}
clear() {
if (this.isEmpty()) return undefined;
this.items = {};
this.count = 0;
}
toString() {
if (this.isEmpty()) return '';
let objString = `${this.items[0]}`;
for (let i = 0; this.count; i++) {
objString = `${objString},${this.items[i]}`;
}
return objString;
}
}
三、利用栈实现进制转换
function baseConverter(decNumber, base) {
const remStack = new Stack();
const digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let number = decNumber;
let rem;
let baseString = '';
if (!(base >= 2 && base <= 36)) {
return '';
}
while (number > 0) {
rem = Math.floor(number % base); // 求余进栈
remStack.push(rem);
number = Math.floor(number / base); // 除以基底重新赋值
}
while (!(remStack.isEmpty())) {
baseString += digits[remStack.pop()] // 出栈并转化成对应字符
}
return baseString;
}
console.log(baseConverter(1000345,16)); //F4399