即可以从头遍历到尾,又可以从尾遍历到头。
也就是链表相连的过程是双向的,一个节点既有向前连接的引用,也有一个向后连接的引用。
缺点:
每次插入或删除某个节点时,需要处理4个引用,而不是2个
当于单向链表,必然占用内存空间更大
这个时候,node1的prev等于null,node1的next等于node2,node2的prev等于node1,node2的next等于node3,node3的prev等于node2,node3的next等于null
node1.prev=null node1.next = node2
node2.prev=node1 node2.next = node3
node3.prev = node2 node3.next = null
function DoubleLinkeList() {
function Node(data) {
this.data = data;
this.prev = null;
this.next = null;
}
// 包含属性
this.head = null;
this.tail = null;//上一个节点
this.length = 0;
DoubleLinkeList.prototype.oppend = (data) => {
var newNode = new Node(data)
// 判断是否添加的节点是第一个节点
if (this.length == 0) {
this.tail = newNode;
this.head = newNode
} else {
newNode.prev = this.tail
this.tail.next = newNode
this.tail = newNode
}
this.length += 1
}
DoubleLinkeList.prototype.toString = () => {
return this.backWardString()
}
// 向后
DoubleLinkeList.prototype.backWardString = () => {
var current = this.head
var currentString = ''
while (current) {
currentString += current.data
current = current.next
}
return currentString
}
// 向前
DoubleLinkeList.prototype.BeforeWardString = () => {
var current = this.tail;
var currentString = ''
while (current) {
currentString += current.data
current = current.prev
}
return currentString
}
// 插入
DoubleLinkeList.prototype.insert = (position, data) => {
// 首先进行越界判断
if (position < 0 || position > this.length) return null;
var newNode = new Node(data)
//判断是否为空链表
if (this.length == 0) {
this.tail = newNode;
this.head = newNode
} else {
// 判断插入的数据位置是否为首位
if (position == 0) {
this.head.prev = newNode;
newNode.next = this.head;
this.head = newNode
} else if (position == this.length) {
// 判断插入的数据是否为末尾
newNode.prev = this.tail;
this.tail.next = newNode;
this.tail = newNode
} else {
var current = this.head;
var index = 0;
while (index++ < position) {
current = current.next
}
// 修改相对应的指针
newNode.next = current;
newNode.prev = current.prev;
current.prev.next = newNode;
current.prev = newNode
}
}
this.length += 1
}
}
var doubleLinke = new DoubleLinkeList()
doubleLinke.oppend(123)
doubleLinke.oppend(456)
doubleLinke.oppend(789)
doubleLinke.insert(1,666)
console.log(doubleLinke.toString())