单向链表: 插入删除效率比数组高
// 创建节点 Node class Node { constructor(data) { this.data = data; this.next = null; } } class List { constructor() { // 定义一个叫头部的属性用于指向第一个节点 this.head = null; // 长度 this.length = 0; } // 追加节点 append(element) { // 将值变为节点 let newNode = new Node(element); // 判断是否为空链表 if (this.head == null) { this.head = newNode; } else { let current = this.head; while (current.next != null) { // 如何将current后移 current = current.next } current.next = newNode; } // 长度必须加1 this.length++; } isEmpty() { if (this.head == null) { return true; } return false; } clear() { this.head = null this.length = 0 } size() { return this.length } toString(callBack) { let current = this.head; while (current) { callBack(current.data); current = current.next } } // 在任意位置添加一个节点/元素 insert(position, element) { // 越界判断 if (position < 0 || position > this.length) { return false; } // 创建新节点 let newNode = new Node(element); let current = this.head; // 在头部插入 if (position == 0) { newNode.next = this.head; this.head = newNode; } // 在尾部插入 else if (position == this.length) { // 找到尾部节点 while (current.next != null) { current = current.next; } current.next = newNode; } // 在中间插入 else { // 找到正确位置 let index = 0; while (index++ != position - 1) { current = current.next; } newNode.next = current.next; current.next = newNode; } this.length++; return true; } // 在当前数据中的第一个匹配的元素的下标 indexOf(element) { // 遍历链表 let current = this.head; // 方法一 // for (let index = 0; index < this.length; index++) { // // 将链表中的值取出与element比较 // if (current.data === element) { // // 相等 返回下标 // return index; // } // // 不相等 继续遍历 // current = current.next; // } // 方法二 let index = 0 while (current) { // 将链表中的值取出与element比较 if (current.data === element) { // 相等 返回下标 return index; } // 不相等 继续遍历 current = current.next; index++; } // 遍历结束后仍未找到 // 返回-1 return -1; } // 移除特定位置的节点 // 0 removeAt(position) { if (position < 0 || position >= this.length) return false; let current = this.head; // 删除头 if (position == 0) { this.head = this.head.next; } // 尾 else if (position == this.length - 1) { let previous = null while (current.next) { previous = current current = current.next; } previous.next = null; } // 中间 else { // 找到要删除的节点的前一个节点设为当前节点 let index = 0 while (index++ != position - 1) { current = current.next } //将当前节点的next指向当前节点的下一个节点的下一个节点 current.next = current.next.next } this.length--; return true; } remove(element){ return this.removeAt(this.indexOf(element)); } }
原文:https://www.cnblogs.com/ljl-zszy/p/11792646.html