const util = require('util'); /** * 链表节点类 */ class Node { constructor (ele) { this.ele = ele; this.next = null; this.prev = null; } } /** * 链表类 */ class NodeList { constructor (ele) { this.head = null; // 初始化链表的头节点 this.length = 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; newNode.prev = currentNode; } this.length++; } /** * 项链表某个位置插入元素 * @param {*} position * @param {*} ele */ insert (position, ele) { if (position >= 0 && position <= this.length) { let newNode = new Node(ele); let currentNode = this.head; let pre; let index = 0; if (position === 0) { if (currentNode === null) { this.head = newNode; } else { this.head = newNode; newNode.next = currentNode; currentNode.prev = newNode; } } else if (position === this.length) { this.append(ele); return; } else { while (index < position) { pre = currentNode; currentNode = currentNode.next; index++; } newNode.next = currentNode; currentNode.prev = newNode; pre.next = newNode; newNode.prev = pre; } this.length++; } else { return new Error('位置超出范围'); } } removeAt (position) { if (position >= 0 && position < this.length) { 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; if (currentNode && currentNode.next !== null) { currentNode.next.prev = pre; } } this.length--; } 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 G = { name: 'G', 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)); nList.insert(5, G); console.log(' origin: ' + nList); nList.removeAt(5); console.log('now: ' + nList); console.log(util.inspect(nList));