import { ctrlbarStore } from '../store' // mobx data
/**
* 双向链表
*/
class Node {
constructor (key) {
this.prev = null
this.key = key
this.element = {}
this.next = null
}
clear () {
this.value = {}
}
// append 添加元素到 element
append (key, value) {
this.element[key] = value
}
forEach (fn) {
const keys = Object.keys(this.element)
keys.forEach(k => {
fn(k, this.element[k])
})
}
}
class DoublyLinkedList {
constructor () {
this.length = 0
this.head = null
this.tail = null
}
// append 添加元素到尾部
append (key) {
if (!key) throw new Error('key is required')
const node = new Node(key)
if (!this.head) {
this.head = this.tail = node
} else {
let cur = this.head
while (cur && cur.key <= key) {
if (cur.next) {
cur = cur.next
} else {
break
}
}
if (cur.next) {
node.next = cur.next
node.prev = cur
cur.next = node
node.next.prev = node
} else {
this.tail = node
node.prev = cur
cur.next = node
}
}
this.length += 1
ctrlbarStore.canvasCount = this.length
}
getNode (key) {
if (!key) return null
let cur = this.head
let node = null
while (!!cur && !node) {
if (cur.key === key) {
node = cur
} else {
cur = cur.next
}
}
return node
}
getIndexFromKey (key) {
if (!key) return 0
let cur = this.head
let index = 0
while (true) {
index += 1
if (cur.key === key) break
if (!cur.next) {
index = 0
break
}
cur = cur.next
}
return index
}
removeNode (key) {
if (!key) return null
let cur = this.head
let node = null
while (!!cur && !node) {
if (cur.key === key) {
node = cur
} else {
cur = cur.next
}
}
if (!node) return
this.length -= 1
node.prev.next = node.next
if (!node.next) this.tail = node.prev
if (this.head.key === node.key) this.head = null
}
}
export { Node, DoublyLinkedList }
export const canvasStore = new DoublyLinkedList()
前端-定制化链表
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...