01-js数据结构:栈

ES5实现

实现1:方法添加到类上

//声明这个类的构造函数
function Stack(items){
    //用来保存栈里的元素
    this.items = items || [];

    //向栈顶添加元素
    this.push = function(element){
        //push():向数组的末尾添加一个或更多元素,返回新的长度
        this.items.push(element);
    }
    //移除栈顶的元素
    this.pop = function(){
        //pop():删除数组的最后一个元素并返回删除数组的元素
        return this.items.pop();
    }
    //返回栈顶的元素
    this.peek = function(){
        return this.items[this.items.length-1];
    }
    //判断栈是否为空
    this.isEmpty = function(){
        return this.items.length === 0;
    }
    //返回栈里元素的个数
    this.size = function(){
        return this.items.length;
    }
    //移除栈里所有元素
    this.clear = function(){
        // this.items.splice(0, this.items.length);
        this.items = [];
    }
    this.print = function(){
        console.log(this.items.toString());
    }
}

实现2:方法添加到原型上(说是节省内存,我还不太懂)

function Stack(items){
    this.items = items || [];

    Stack.prototype.push = function(element) {
        this.items.push(element);
    }
    Stack.prototype.pop = function() {
        return this.items.pop();
    }
    Stack.prototype.peek = function() {
        return this.items[this.items.length - 1];
    }
    Stack.prototype.isEmpty = function() {
        return this.items.length === 0;
    }
    Stack.prototype.size = function() {
        return this.items.length;
    }
    Stack.prototype.print = function() {
        console.log(this.items.toString());
    }
    Stack.prototype.clear = function() {
        this.items = [];
    }
}

一些栈应用案例:

数据结构使用上面两种都可

1. 十进制转二进制
function dec2bin(decNumber){
    let stack = new Stack();
    while(decNumber > 0){
        stack.push(decNumber % 2);
        decNumber = Math.floor(decNumber / 2);
    }
    let binaryStr = '';
    while(!stack.isEmpty()){
        binaryStr += stack.pop();
    }
    return binaryStr;
}

参考🔗:js实现栈结构

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值