insert() 方法 , 在链表特定位置添加节点
实现代码
// 返回的链表return class LinkedList {constructor() {// 初始化, 当前的链表length.set(this, 0); // 长度为0head.set(this, null); // 头部数据为 null}// 链表的方法// append 在链表最后添加节点append(element) {// 创建节点let node = new Node(element),// 声明一个变量,用于保存链表的头部数据current;// 判断链表是否有数据if (this.getHeader() === null) {// 当链表为空的情况下head.set(this, node); // 直接添加} else {// 链表头部不为空// 找到链表最末的节点, 让最末的节点的 next 指向添的nodecurrent = this.getHeader(); // 获取当前的head// 判断当前节点的next存在while (current.next) {// next ++ ,一直循环current = current.next;}// 进行while循环完后,current 就为最后的节点。// 然后进行赋值current.next = node;// 赋值后,让链表长度 +1// 使用size获取链表的长度let l = this.size();l++; // 让链表的长度加一length.set(this, l); // 重新赋值}}// 在链表任何位置插入数据insert(position, element) {// position : 链表的位置// element : 插入的节点数据// 判断当前链表if (position >= 0 && position <= this.size()) {// 创建节点let node = new Node(element),// 使用current 保存到获取链表的头部current = this.getHeader(),index = 0,previous;// 判断链表if (position === 0) {// 表示在链表的头部插入数据node.next = current; // 将初始的链表的指针设置为新创建的nodehead.set(this, node); // 链表赋值} else {// 表示插入的节点在某一个节点前while (index++ < position) {previous = current;current = current.next;}// 将它们的next() 指向另一个nodenode.next = current;previous.next = node;}// 让length ++// 使用size获取链表的长度let l = this.size();l++; // 让链表的长度加一length.set(this, l); // 重新赋值// 追加后,返回head, 查看headconsole.log(this.getHeader()); // 返回是否插入成功return true;} else {// 插入不成功return false;}}// 判断链表的头部getHeader() {return head.get(this);}// 返回链表的长度size() {return length.get(this);}}// 实例化输出let list = new LinkedList();list.append(0);list.append(1);list.append(2);list.append(3);// insert方法的实现和数组的插入方法一样// var arr = [0, 1, 2, 3, 4];// arr.splice(2, 0, 1.5);// console.log(arr);console.log(list.insert(2, 1.5)); // 2: 插入的位置, 1.5 插入的数据

输出结果

