链表题目
https://leetcode-cn.com/problemset/algorithms/?topicSlugs=linked-list
首先基本上会把arr=[1,2,3] ->转为1->2->3 这样的结构
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Node { constructor(item) { this.item = item this.next = null } } class linkedList { constructor() { this.head = null this.length = 0 } append(item) { const node = new Node(item) let current = this.head let previous = null if (!current) this.head = node else { while (current) { previous = current current = current.next } previous.next = node } this.length++ } toString() { const arr = [] let current = this.head if (!current) return '' while (current) { arr.push(current.item) current = current.next } return arr.join('->') } }
const arr = [1, 1, 2] const link = new linkedList() arr.forEach(item => link.append(item)) console.log(link.toString()); //1->1->2
至此就完成了数组转链表的操作
使用 :link.head = deleteDuplicates(link.head) deleteDuplicates是一个举例子 就是操作函数了
删除链表中的节点
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
function deleteNode(node) { let current = link.head let previous = null while (current) { if (current.item === node) break previous = current current = current.next } previous.next = current.next console.log(link.toString()); } deleteNode(node)