JavaScript数组结构(一)栈

一、定义

栈遵循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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值