加入收藏 | 设为首页 | 会员中心 | 我要投稿 PHP编程网 - 黄冈站长网 (http://www.0713zz.com/)- 数据应用、建站、人体识别、智能机器人、语音技术!
当前位置: 首页 > 综合聚焦 > 编程要点 > 资讯 > 正文

前端进阶:链表的概念和应用

发布时间:2021-06-04 16:03:36 所属栏目:资讯 来源:互联网
导读:副标题#e# 为了实现链表以及链表的操作,首先我们需要先定义链表的基本结构,第一步就是定义节点的数据结构。我们知道一个节点会有自己的值以及指向下一个节点的引用,所以可以这样定义节点: letNode=function(el){ this.el=el; this.next=null; } 接下来

由代码可知我们在节点中会有上一个节点的引用以及下一个节点的引用,同时这里笔者添加了头部节点和尾部节点方便大家操作。大家可以根据自己的需求实现双向链表的功能,这里笔者提供一份自己实现的代码,可以参考交流一下:

// 双向链表, 每一个元素都有一个存储元素自身的节点和指向上一个元素引用以及下一个元素引用的节点组成 

function doubleLinkedList() { 

  let Node = function(el) { 

      this.el = el; 

      this.previous = null; 

      this.next = null; 

  } 

  let length = 0 

  let head = null  // 用来存储头部元素的引用 

  let tail = null  // 用来存储尾部元素的引用 

 

  // 尾部添加元素 

  this.append = (el) => { 

    let node = new Node(el) 

    if(!head) { 

      head = node 

    }else { 

      tail.next = node; 

      node.previous = tail; 

    } 

    tail = node; 

    length++ 

  }; 

  // 插入元素 

  this.insert = (pos, el) => { 

    if(pos >=0 && pos < length) { 

      let node = new Node(el); 

      if(pos === length - 1) { 

        // 在尾部插入 

        node.previous = tail.previous; 

        node.next = tail; 

        tail.previous = node; 

        length++; 

        return true 

      } 

      let current = head, 

          i = 0; 

      while(i < pos) { 

        current = current.next; 

        i++ 

      } 

      node.next = current; 

      node.previous = current.previous; 

      current.previous.next = node; 

      current.previous = node; 

      length ++; 

      return true     

    }else { 

      throw new RangeError(`插入范围有误`) 

    } 

  }; 

  // 移除指定位置的元素 

  this.removeAt = (pos) => { 

    // 检测边界条件 

    if(pos < 0 || pos >= length) { 

      throw new RangeError(`删除范围有误`) 

    }else { 

      if(length) { 

        if(pos === length - 1) { 

          // 如果删除节点位置为尾节点,直接删除,节省查找时间 

          let previous = tail.previous; 

          previous.next = null; 

          length --; 

          return tail.el 

        }else { 

          let current = head, 

              previous = null, 

              next = null, 

              i = 0; 

          while(i < pos) { 

(编辑:PHP编程网 - 黄冈站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

推荐文章
    热点阅读