链表
有点像⽕⻋,⻋厢和⻋厢之间链接,有点是可以随时替换⻋厢,react最新架构的fifiber,就是从树变成
了链表,能够让diffff任务随时中断
class Node{
constructor(element){
this.element = element
this.next = null
}
}
class LinkedList{
constructor(){
this.head = null
this.current
this.length = 0
}
append(element){
const node = new Node(element)
if (this.head === null) { // 插⼊第⼀个链表
this.head = node
} else {
this.current = this.head
while (this.current.next) { // 找到最后⼀个节点
this.current = this.current.next
}
this.current.next = node
}
this.length++
}
// 移除指定位置元素
removeAt(position) {
if (position > -1 && position < this.length) {
let previous
let index = 0
if (position === 0) { // 如果是第⼀个链表的话, 特殊对待
this.head = this.head.next
} else
this.current = this.head
while (index < position) { // 循环找到当前要删除元素的位置
previous = this.current
this.current = this.current.next
index++
}
previous.next = this.current.next
}
this.length--
}
}
// 在指定位置加⼊元素
insert (position, element) {
const node = new Node(element)
let index = 0
let current, previous
if (position > -1 && position < this.length + 1) {
if (position === 0) { // 在链表最前插⼊元素
current = this.head
this.head = node
this.head.next = current
} else {
current = this.head
while (index < position) { // 同 removeAt 逻辑, 找到⽬标位置
previous = current
current = current.next
index++
}
previous.next = node // 在⽬标位置插⼊相应元素
node.next = current
}
this.length++
}
}
// 链表中是否含有某个元素, 如果有的话返回相应位置, ⽆的话返回 -1
indexOf(element) {
let index = 0
this.current = this.head
while (index < this.length) {
if (this.current.element === element) {
return index
}
this.current = this.current.next
index++
}
return -1
}
// 移除某元素
remove(element) {
const position = this.indexOf(element)
this.removeAt(position)
}
// 获取⼤⼩
size () {
return this.length
}
// 获取最开头的链表
getHead () {
return this.head
}
// 是否为空
isEmpty () {
return this.length === 0
}
// 打印链表元素
log () {
this.current = this.head
let str = this.current.element
while (this.current.next) {
this.current = this.current.next
str = str + ' ' + this.current.element
}
console.log(str)
return str
}
}
// 测试⽤例
var linkedList = new LinkedList()
linkedList.append(5)
linkedList.append(10)
linkedList.append(15)
linkedList.append(20)
linkedList.log() // '5 10 15 20'
linkedList.removeAt(1)
linkedList.log() // '5 15 20'
linkedList.insert(1, 10)
linkedList.log()
索引: O(n)
搜索: O(n)
插⼊: O(1)
移除: O(1)
集合