当前位置: 首页 > news >正文

es6 实现单链表

第一种
/*
* * 链表节点类 */ class Node { constructor(ele) { this.ele = ele; this.next = null; } } /** * 链表类 */ class NodeList { constructor(ele) { this.head = new Node(ele); //初始化链表的头节点 } findPreNode(item) { let currentNode = this.head; while (currentNode && currentNode.next && currentNode.next.ele !== item) { if (currentNode.next) { currentNode = currentNode.next; } else { currentNode = null; } } return currentNode; } findNode(item) { let currentNode = this.head; while (currentNode && currentNode.ele !== item) { if (currentNode.next) { currentNode = currentNode.next; } else { currentNode = null; } } return currentNode; } findLastNode() { let currentNode = this.head; while (currentNode.next) { currentNode = currentNode.next; } return currentNode; } append(newItem, preItem) { let newNode = new Node(newItem); if (preItem) { // 判读是否是插入到指定节点后面,如果不是则插入到最后一个节点。 let currentNode = this.findNode(preItem); newNode.next = currentNode.next; currentNode.next = newNode; } else { let lastNode = this.findLastNode(); lastNode.next = newNode; } } remove(item) { let preNode = this.findPreNode(item); // 找到前一节点,将前一节点的next指向该节点的next if (preNode.next != null) { preNode.next = preNode.next.next; } } toString() { let currentNode = this.head; let strList = []; while (currentNode.next) { strList.push(JSON.stringify(currentNode.ele)); currentNode = currentNode.next; } strList.push(JSON.stringify(currentNode.ele)); return strList.join(' ==> ') } } let A = { name: 'A', age: 10 }, B = { name: 'B', age: 20 }, C = { name: 'C', age: 30 }, D = { name: 'D', age: 40 }, E = { name: 'E', age: 50 }; let nList = new NodeList(A); nList.append(C); nList.append(B); nList.append(D); nList.append(E, A); console.log(" " + nList); nList.remove(C); console.log(" now " + nList)
origin: {"name":"A","age":10} ==> {"name":"E","age":50} ==> {"name":"C","age":30} ==> {"name":"B","age":20} ==> {"name":"D","age":40}
 now: {"name":"A","age":10} ==> {"name":"E","age":50} ==> {"name":"B","age":20} ==> {"name":"D","age":40}

 

第二种
/**
 * 链表节点类
 */
class Node {
  constructor (ele) {
    this.ele = ele;
    this.next = null;
  }
}
/**
 * 链表类
 */
class NodeList {
  constructor (ele) {
    this.head = null; // 初始化链表的头节点
    this.lenght = 0;
  }
  /**
                     *  尾部插入数据
                     * @param {*} ele
                     */
  append (ele) {
    let newNode = new Node(ele);
    let currentNode;
    if (this.head === null) {
      this.head = newNode;
    } else {
      currentNode = this.head;
      while (currentNode.next) {
        currentNode = currentNode.next;
      }
      currentNode.next = newNode;
    }
    this.lenght++;
  }/**
   * 项链表某个位置插入元素
   * @param {*} position
   * @param {*} ele
   */
  insert (position, ele) {
    if (position >= 0 && position <= this.lenght) {
      let newNode = new Node(ele);
      let currentNode = this.head;
      let pre;
      let index = 0;
      if (position === 0) {
        newNode.next = currentNode;
        this.head = newNode;
      } else {
        while (index < position) {
          pre = currentNode;
          currentNode = currentNode.next;
          index++;
        }
        newNode.next = currentNode;
        pre.next = newNode;
      }
      this.lenght++;
    } else {
      return new Error('位置超出范围');
    }
  }
  removeAt (position) {
    if (position >= 0 && position < this.lenght) {
      let currentNode = this.head;
      let pre;
      let index = 0;
      if (position === 0) {
        this.head = currentNode.next;
      } else {
        while (index < position) { // 1,2,3
          pre = currentNode;
          currentNode = currentNode.next;
          index++;
        }
        pre.next = currentNode.next;
      }
      this.lenght--;
    } else {
      return new Error('删除位置有误');
    }
  }
  find (ele) {
    let currentNode = this.head;
    let index = 0;
    while (currentNode) {
      if (JSON.stringify(currentNode.ele) === JSON.stringify(ele)) {
        return index;
      } else {
        index++;
        currentNode = currentNode.next;
      }
    }
    return -1;
  }
  // 判断链表是否为空
  isEmpty () {
    return this.length === 0;
  }
  size () {
    return this.length;
  }
  // 返回头
  getHead () {
    return this.head;
  }
  toString () {
    let current = this.head;
    let str = '';
    while (current) {
      str += JSON.stringify(current.ele) + ' => ';
      current = current.next;
    }
    return str;
  }
}
let A = { name: 'A', age: 10 };

let B = { name: 'B', age: 20 };

let C = { name: 'C', age: 30 };

let D = { name: 'D', age: 40 };

let E = { name: 'E', age: 50 };

let nList = new NodeList();

nList.append(A);
nList.append(C);
nList.append(B);
nList.append(D);
nList.append(E);
// console.log(JSON.stringify(nList, null, 2));
console.log(' origin: ' + nList);
nList.removeAt(2);
console.log(' now: ' + nList);

origin: {"name":"A","age":10} => {"name":"C","age":30} => {"name":"B","age":20} => {"name":"D","age":40} => {"name":"E","age":50} =>
now: {"name":"A","age":10} => {"name":"C","age":30} => {"name":"D","age":40} => {"name":"E","age":50} =>

 

转载于:https://www.cnblogs.com/xiaosongJiang/p/10878718.html

相关文章:

  • maven中spring jar包版本号不统一出现报错
  • 从零开始学Node.js(七_增)
  • python基础知识8——常见内置模块
  • vim跳转到某行
  • Knative Eventing 中如何实现 Registry 事件注册机制
  • jquery.i18n.properties前端国际化方案
  • cursor-spacing 软键盘和input的距离
  • spring cloud服务注册与发现无法发现的可能原因
  • Python中的列表(3)
  • 【Java基础】图片压缩
  • Nginx反向代理,负载均衡,redis session共享,keepalived高可用
  • Python进阶之路 3.5.4 循环中的else语句
  • 【更新】Stimulsoft Reports v2019.3.1发布,新增对OData v4的支持功能
  • 7天瓜分36万美妆,勇敢“晒丫”才是年轻人的生活方式
  • 宜信开源微服务任务调度平台(SIA-TASK)
  • Android开发 - 掌握ConstraintLayout(四)创建基本约束
  • Apache Spark Streaming 使用实例
  • crontab执行失败的多种原因
  • css的样式优先级
  • JavaScript/HTML5图表开发工具JavaScript Charts v3.19.6发布【附下载】
  • JSONP原理
  • Mocha测试初探
  • October CMS - 快速入门 9 Images And Galleries
  • Spring Cloud Feign的两种使用姿势
  • Unix命令
  • Windows Containers 大冒险: 容器网络
  • windows下如何用phpstorm同步测试服务器
  • XForms - 更强大的Form
  • 互联网大裁员:Java程序员失工作,焉知不能进ali?
  • 基于OpenResty的Lua Web框架lor0.0.2预览版发布
  • 基于阿里云移动推送的移动应用推送模式最佳实践
  • 聊聊sentinel的DegradeSlot
  • 如何优雅地使用 Sublime Text
  • 使用Tinker来调试Laravel应用程序的数据以及使用Tinker一些总结
  • 微服务入门【系列视频课程】
  • 在weex里面使用chart图表
  • 教程:使用iPhone相机和openCV来完成3D重建(第一部分) ...
  • 如何通过报表单元格右键控制报表跳转到不同链接地址 ...
  • ​油烟净化器电源安全,保障健康餐饮生活
  • # 安徽锐锋科技IDMS系统简介
  • # 数论-逆元
  • #控制台大学课堂点名问题_课堂随机点名
  • #数学建模# 线性规划问题的Matlab求解
  • (2)Java 简介
  • (JS基础)String 类型
  • (Redis使用系列) Springboot 实现Redis 同数据源动态切换db 八
  • (黑马出品_高级篇_01)SpringCloud+RabbitMQ+Docker+Redis+搜索+分布式
  • (排序详解之 堆排序)
  • (企业 / 公司项目)前端使用pingyin-pro将汉字转成拼音
  • (转)可以带来幸福的一本书
  • (转)原始图像数据和PDF中的图像数据
  • *p++,*(p++),*++p,(*p)++区别?
  • .NET 4.0网络开发入门之旅-- 我在“网” 中央(下)
  • .NET8.0 AOT 经验分享 FreeSql/FreeRedis/FreeScheduler 均已通过测试
  • .NetCore 如何动态路由