classNode{constructor(element, next){this.element = element
this.next = next === undefined ?null: next
}}
2.创建LinkedList类(里面包含插入节点、删除节点、查找节点位置方法)
classLinkedList{constructor(){this.size =0this.head =null}// 插入节点append(element){let node =newNode(element)if(this.head ===null){this.head = node
}else{let current =this.getNode(this.size -1)
current.next = node
}this.size++}// 根据位置插入节点 appendAt(position, element){if(position <0&& position >this.size){thrownewError('position out of range')}let node =newNode(element)if(position ===0){
node.next =this.head
this.head = node
}else{let pre =this.getNode(position -1)
node.next = pre.next
pre.next = node
}this.size ++}// 根据位置删除节点removeAt(position){if(position <0&& position >=this.size){thrownewError('position out of range')}if(position ===0){let current =this.head
this.head = current.next
}else{let pre =this.getNode(position -1)let current =this.getNode(position)
pre.next = current.next
}this.size--}// 查找node索引值indexOf(element){let node =newNode(element)let current =this.head
for(let i =0; i <this.size; i ++){if(node.element == current.element){return i
}
current = current.next
}}getNode(index){if(index <0&& index >=this.size){thrownewError('out range')}let current =this.head
for(let i =0; i < index; i++){
current = current.next
}return current
}}