接着我们的第一篇文章,继续实现双向链表的方法。这是我们定义好的双向链表的数据结构不要忘了:
function TwoWayLinkList() {
// 属性
this.head = null
this.tail = null
this.length = 0
// 用于创建节点的内部类
function Node(data) {
this.data = data
this.prev = null
this.next = null
}
}
双向链表与单向链表的区别是在头部和尾部都能找到我们的元素
然后把新节点的prev指向上一个节点。tail中指向的就是上一个节点(第一个节点)。
最后需要移动tail,将其指向最后一个节点。
/**
* 1.append()
* */
TwoWayLinkList.prototype.append = function (data) {
// 创建节点
var newNode = new Node(data)
if (this.length == 0) {
this.head = newNode
this.tail = newNode
} else {
this.tail.next = newNode
newNode.prev = this.tail
this.tail = newNode
}
this.length += 1
}