单向链表的优势:在同一个位置插入或者删除多次,时间复杂度为 O(1)
// 生成一个单向链表 // 辅助类,用来生成结点 let Node = function(element){ this.element = element; this.next = null; } // 链表(查询,添加,插入,删除,清空) class LinkedList { // 静态属性写在构造函数 constructor() { this.length = 0; this.head = null; } // 查询某位置的结点,position 从 0 开始 getElementAt(position) { if(position < 0 || position >= this.length){ return null; } let current = this.head; // i 最大 position - 1,倒数第二个,指针移到下一个结点 for (let i = 0; i < position; i++) { current = current.next; } return current; } // 在链表末尾增加结点 append(element) { let node = new Node(element); // 空链表给头部结点赋值成第一个结点 if(this.head === null){ this.head = node; }else{ // 已存在 遍历获取最后一个结点 最后结点 next 指向 node let origin = this.getElementAt(this.length - 1); origin.next = node; } this.length++; } // 在链表某个位置插入1个结点 insert(position, element) { if(position < 0 || position > this.length){ return; }else{ let node = new Node(element); if(this.head === null){ this.head = node; }else{ if(position === 0){ node.next = this.head; this.head = node; }else{ let origin = this.getElementAt(position - 1); node.next = origin.next; origin.next = node; } } this.length++; } } // 在链表某个位置插入n个结点 insertMulti(position, elements) { let flag = true; let origin; if(position < 0 || position > this.length){ return; }else{ elements.forEach((element, inx) => { let node = new Node(element); if(this.head === null){ this.head = node; }else{ if(flag){ // 要插入的位置前一位 origin = this.getElementAt(position - 1); flag = false; } if(position === 0){ node.next = this.head; this.head = node; }else{ node.next = origin.next; origin.next = node; } } this.length++; }); } } // 在链表某个位置删除1个结点 delete(position) { if(position < 0 || position > this.length){ return; }else{ if(position === 0){ this.head = this.head.next; }else{ let specified = this.getElementAt(position - 1); specified.next = specified.next.next; this.length--; } } } // 在链表某个位置删除n个结点 deleteMulti(position, count) { let flag = true; let specified; for(let i = 0; i < count; i++){ if(this.head === null || (flag && position + count > this.length) || position < 0 || position > this.length){ return ; }else{ if(position === 0){ this.head = this.head.next; flag = false; }else{ if(flag){ // 要删除的位置前一位 specified = this.getElementAt(position - 1); flag = false; } specified.next = specified.next.next; } } this.length--; } } // 清空链表 clear() { this.head = null; this.length = 0; } }