// 节点类function Node(val) {this.val = valthis.next = null}// 链表类function NodeList() {this.head = nullthis.length = 0// 向链表末尾追加元素this.push = push// 在值为 val 的节点后面添加一个值为 newVal 的节点this.insertAfter = insertAfter// 在链表中查找值为 val 的节点this.find = find// 在链表中查找值为val 的节点的前一个节点this.findPrev = findPrev// 删除链表中值为 val 的节点this.remove = remove// 将值为val 的节点修改为 newValthis.update = update// 打印链表this.toString = toString}function push(val) {let node = new Node(val)// 第一个节点if (this.head === null) {this.head = node} else {let current = this.head// 找到最后一个节点while (current.next !== null) {current = current.next}// 最后一个节点后面追加节点current.next = node}this.length++}function insertAfter(val, newVal) {let current = this.find(val)if (current === null) return -1let node = new Node(newVal)// 先将当前节点的指向给到新节点的指向 !node.next = current.next// 再将当前节点指向新节点current.next = nodethis.length++}function find(val) {// 空链表if (this.head === null) return nulllet current = this.head// 查找到最后一个节点之前while (current.next !== null) {if (current.val === val) return currentcurrent = current.next}// 判断最后1个节点if (current.val === val) return currentreturn null}function findPrev(val) {// 空链表或者查找第一个节点的前一个节点均查不到if (this.head === null || this.head.val === val) return nulllet current = this.head// 最后一个节点不进循环, 最后一个节点不可能是某个节点的前一个节点while (current.next !== null) {if (current.next.val === val) return currentcurrent = current.next}return null}function remove(val) {let current = this.find(val)if (current === null) return -1else {let prev = this.findPrev(val)if (prev !== null) {prev.next = current.next} else {// prev === null 即删第一个节点 让当前节点的下一个节点第2个节点为头this.head = current.next}}this.length--}function update(val, newVal) {let current = this.find(val)if (current === null) return -1current.val = newVal}function toString() {let current = this.headlet str = ''let index = 0while (current !== null) {// str += index + current.val + (current.next ? ' -> ' : '')str += `(${index}) ${current.val}${current.next ? ' -> ' : ''}`current = current.nextindex++}console.log(str)}// 测试代码let nodeList = new NodeList()nodeList.push('1st element')nodeList.push('2nd element')nodeList.push('3rd element')nodeList.push('4th element')console.log('find', nodeList.find('1st element'))console.log('find', nodeList.find('2nd element'))console.log('find', nodeList.find('3rd element'))console.log('find', nodeList.find('4th element'))console.log('findPrev', nodeList.findPrev('1st element'))console.log('findPrev', nodeList.findPrev('2nd element'))console.log('findPrev', nodeList.findPrev('3rd element'))console.log('findPrev', nodeList.findPrev('4th element'))nodeList.remove('4th element')console.log('length', nodeList.length, 'nodeList', nodeList)nodeList.insertAfter('2nd element', '2nd element 2')console.log('length', nodeList.length, 'nodeList', nodeList)nodeList.update('2nd element', '2nd element update')console.log('length', nodeList.length, 'nodeList', nodeList)nodeList.toString()// 原文链接:https://blog.csdn.net/aSmallProgrammer/article/details/106137774
