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

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

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

            current = current.next 

            i++ 

          } 

          previous = current.previous; 

          next = current.next; 

          previous.next = next; 

          length --; 

          return current.el 

        } 

      }else { 

        return null 

      } 

    } 

  }; 

  // 移除指定节点 

  this.remove = (el) => { 

    let idx = this.indexOf(el); 

    this.removeAt(idx); 

  }; 

  // 查询指定位置的链表元素 

  this.get = (index) => { 

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

      return undefined 

    }else { 

      if(length) { 

        if(index === length - 1) { 

          return tail.el 

        } 

        let current = head, 

            i = 0; 

        while(i < index) { 

          current = current.next 

          i++ 

        } 

        return current.el 

      }else { 

        return undefined 

      } 

    } 

  } 

  // 查询节点所在位置 

  this.indexOf = (el) => { 

    let idx = -1, 

        current = head, 

        curIdx = -1; 

    while(current) { 

      idx++ 

      if(current.el === el) { 

        curIdx = idx; 

        break; 

      } 

      current = current.next; 

    } 

    return curIdx 

  }; 

  // 判断链表是否为空 

  this.isEmpty = () => { 

    return length === 0 

  }; 

  // 返回链表长度 

  this.size = () => { 

    return length 

  }; 

  // 将链表转化为数组返回 

  this.toArray = () => { 

    let current = head, 

        results = []; 

    while(current) { 

      results.push(current.el); 

      current = current.next; 

    } 

    return results 

  }; 

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

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

推荐文章
    热点阅读