//双向链表
class Node {
constructor (data) {
this.data = data
this.prev = null
this.next = null
}
}
class DoubleList {
constructor () {
this.head = null
this.tail = null
this.length = 0
}
//追加数据
append (data) {
// 创建新节点
let newNode = new Node(data)
// 链表为空
if (!this.head) {
this.head = newNode
this.tail = newNode
}else {
newNode.prev = this.tail
this.tail.next = newNode
this.tail = newNode
}
this.length++
return true
}
//插入数据
insert (posi, data) {
if (posi < 0 || posi > this.length) return false
//创建新节点
let newNode = new Node(data)
if (posi == 0) {
if (!this.head) {
this.head = newNode
this.tail = newNode
}else {
newNode.next = this.head
this.head.prev = newNode
this.prev = newNode
}
}else if (this.length == posi) {
newNode.prev = this.tail
this.tail.next = newNode
this.tail = newNode
}else {
// 保存头节点
// while (index++ < posi - 1) {
// current = current.next
// }
// newNode.prev = current
// newNode.next = current.next
// current.next.prev = newNode
// current.next = newNode
let current = ''
let index = 0
if (posi < this.length / 2) {
current = this.head
index = 0
while (index++ < posi - 1) {
current = current.next
}
}else {
index = this.length - 1
current = this.tail
while (index-- > posi - 1) {
current = current.prev
}
}
newNode.next = current
newNode.prev = current.prev
current.prev.next = newNode
current.prev = newNode
}
this.length++
return true
}
//查找第一次出现的数据
indexOf (data) {
let current = this.head
let index = 0
while (current) {
if (current.data === data) {
return index
}
index++
current = current.next
}
return -1
}
//查找到最后一次出现的数据
lastIndexOf (data) {
let current = this.tail
let index = this.length - 1
while (current) {
if (current.data === data) {
return index
}
index--
current = current.prev
}
return -1
}
removeAt (posi) {
if (posi < 0 || posi > this.length -1) return false
if (posi == 0) {
if (this.length == 1) {
this.head = null
this.tail = null
}else {
// this.head.next.prev = null
// this.head = this.head.next
this.head = this.head.next
this.head.prev = null
}
}else if (posi == this.length - 1) {
this.tail = this.tail.prev
this.tail.next = null
}else {
let current = ''
let index = 0
if (posi < this.length / 2) {
current = this.head
index = 0
while (index++ < posi - 1) {
current = current.next
}
}else {
index = this.length - 1
current = this.tail
while (index-- > posi - 1) {
current = current.prev
}
}
current.next = current.next.next
current.next.prev = current
}
this.length--
return true
}
remove (data) {
//删除所有data的数据
while (this.indexOf(data) != -1) {
//删除第一个出现的data数据
this.removeAt(this.index(data))
}
return true
}
isEmpty () {
return this.head == null
}
size () {
return this.length
}
}
let dList = new DoubleList()
dList.insert(0, 'a')
dList.append('b')
dList.append('c')
dList.append('d')
dList.append('e')
dList.append('f')
dList.append('g')
dList.insert(4, 'h')
dList.append('h')
dList.removeAt(4)