JavaScript一种类似栈或链表的结构实现

背景

通过JavaScript实现了一种类似栈或链表的结构,可用于面包屑导航、操作记录缓存等场景,实现了增加、移除、长度返回、数据返回、跳转等操作。

代码

var StackHelper = function () {
    this.head = null;
    this.tail = null;
    // 可通过datas遍历元素
    this.datas = [];

    // stackItem = {pre:o, next:o, data:obj}

    /**
     * pop() 移除栈顶元素(不会返回栈顶元素的值)
       push(obj) 在栈顶增加元素
       size() 返回栈中元素数目
       top() 返回栈顶元素
       jump(index) 跳转到从底部开始的某个索引,即抛弃栈顶部的一些元素。
     * */

    // 在栈顶增加元素
    /*
    在栈顶增加元素
    */
    this.push = function (obj) {
        var stackItem = {
            pre: this.datas.length > 0 ? this.datas[this.datas.length - 1] : null,
            next: null,
            data: obj
        };
        this.datas.length > 0 ? this.datas[this.datas.length - 1].next = stackItem : this.head = stackItem;
        this.tail = stackItem;
        this.datas.push(stackItem);
    }

    this.pop = function () {
        if (this.datas.length > 0) {
            delete this.datas[this.datas.length - 1];
            if (this.datas.length > 0) {
                this.datas[this.datas.length - 1].next = null;
                this.tail = this.datas[this.datas.length - 1];
            } else {
                this.head = null;
                this.tail = null;
            }
        }
    }

    this.size = function () {
        return this.datas.length;
    }

    this.top = function () {
        return this.tail;
    }

    this.jump = function (index) {
        if (index >= this.datas.length) {
            return;
        }

        var _ds = [];
        for (var i = 0; i <= index; i++) {
            _ds.push(this.datas[i]);
        }

        this.datas = _ds;
        this.datas[this.datas.length - 1].next = null;
        this.tail = this.datas[this.datas.length - 1];
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值