【前端】JavaScript 数据结构 -- 链表

JavaScript 数据结构 – 链表

1. 链表定义

1.1 定义

链表是一种使用任意单元存储线性表元素的数据结构,是一种链式存储的线性表,该种数据结构的特点:

  1. 方便插入删除
  2. 不支持随机存取
  3. 存储单元(元素)在内存中不一定连续
  4. 链表中元素存储元素信息外,还含有指向下一个元素的指针域信息

1.2 示意图

在这里插入图片描述

  1. head:链表头
  2. Node:元素(结点)
  3. info:元素信息
  4. next:指向下一元素的指针域

1.3 链表支持方法

  1. add(node):增加一个结点
  2. remove():删除一个结点
  3. size():返回链表长度
  4. isEmpty():检测链表是否为空
  5. get(index):获取 index 下的元素

2. JavaScript 链表的实现

2.1 字面量声明

let list = {
   
    head:null,
    
    add: function(data) {
   
        let node = {
   
            data: data,
            next: null
        }
        if (this.head === null) {
   
            this.head = node
        } else {
   
            let pre = this.head;
            let next = this.head.next;
            while (next !== null) {
   
                pre = next;
                next = next.next;
            }
            pre.next = node;
        }
    },
    
    remove: function() {
   
        if (this.head === null || this.head.next === null) {
   
            this.head = null;
            return;
        }

        let pre = this.head;
        let next = this.head.next;
        while (next.next !== null) {
   
            pre = next;
            next = pre.next;
        }
        console.log(pre.data);
        pre.next = null;
    },

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值