4、栈

 

栈是一种高效的数据结构,因为数据只能在栈顶添加或删除,被称为一种后进先出(LIFO)的数据结构。
push():入栈
pop():出栈
peek():只返回栈顶元素,而不删除它

function Stack() {
    let items = [];

    this.push = element => {
        items.push(element);
    };

    this.pop = () => {
        return items.pop();
    };

    this.peek = () => {
        return items[items.length - 1];
    };

    this.isEmpty = () => {
        return items.length == 0;
    };

    this.size = () => {
        return items.length;
    };

    this.clear = () => {
        items = [];
    };

    this.print = () => {
        console.log(items.toString());
    };
}


------------------------------------------------------------

// 将数字转换为二进制、八进制以及十六进制
function baseConverter(num, base) {
    let remStack = new Stack();
    let digits = "0123456789ABCDEF";
    let baseStr = "";

    while (num > 0) {
        remStack.push(Math.floor(num % base));
        num = Math.floor(num / base);
    }

    while( !remStack.isEmpty()) {
        baseStr += digits[remStack.pop()];
    }

    return baseStr;
}


console.log(baseConverter(1100, 2))
console.log(baseConverter(1100, 8))
console.log(baseConverter(1100, 16))

------------------------------------------------------------

// 判断是否回文
function isPalindrome(word){
    let s = new Stack();
    for(let i=0; i<word.length; ++i){
        s.push(word[i]);
    }

    let rword = "";
    while(s.size() > 0){
        rword += s.pop();
    }

    if(rword === word){
        return true;
    }else{
        return false;
    }
}

let word = "helleh";
if(isPalindrome(word)){
    log(word + " 是回文!");
}else{
    log(word + " 不是回文!");
}

------------------------------------------------------------

// 递归
function factorial1(n){
    if (n === 0){
        return 1;
    } else {
        return n * factorial1(n - 1);
    }
}

function factorial2(n){
    let s = new Stack();
    while(n > 1){
        s.push(n--);
    }

    let product = 1;
    while(s.size() > 0){
        product *= s.pop();
    }
    return product;
}

console.log(factorial1(5));
console.log(factorial2(5));

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值