8. JavaScript数据结构之栈及十进制转化二进制

27 阅读1分钟

栈(stack)是一种受限线性表,后进先出(LIFO)

其限制仅允许在表的一端进行插入和删除操作,这一端称为栈顶,相对的把另一端称为栈底

栈的实现

数组

function Stack(){
    // 栈属性
    this.items = [];

    // 栈操作
    // 1.进栈
    Stack.prototype.push = function(element) {
        this.items.push(element)
    }
    // 2.出栈
    Stack.prototype.pop = function () {
        return this.items.pop();
    }
    // 3.获取栈顶
    Stack.prototype.peek = function () {
        return this.items[this.items.length - 1]
    }
    // 4.判断为空
    Stack.prototype.isEmpty = function () {
        return this.items.length == 0;
    }
    // 5.获取元素个数
    Stack.prototype.size = function () {
        return this.items.length;
    }
    // 6.toString()
    Stack.prototype.toString = function () {
        let str = ''
        this.items.forEach(element => {
            str += element+" ";
        });
        return str;
    }
}

链表

十进制转化二进制问题

function decTwobin(num){
    var stack = new Stack();
    // num不等于0继续循环
    while(num > 0){
        // 余数进栈
        stack.push(num % 2);
        // num向下取整
        num = Math.floor(num / 2);
    }
    var str = '';
    // 全部出栈
    while(!stack.isEmpty()){
        str += stack.pop()
    }
    return str
}   
console.log(decTwobin(100));