链表剩下的常用操作
LinkedList.prototype.get = function (position) {
if (position < 0 || position >= this.length) return null
var current = this.head
var index = 0
while (index++ < position) {
current = current.next
}
return current.data
}
LinkedList.prototype.indexOf = function (data) {
var current = this.head
var index = 0
while (current) {
if (current.data == data) {
return index
}
current = current.next
index += 1
}
return -1
}
LinkedList.prototype.update = function (position, newdata) {
if (position < 0 || position >= this.length) return false
var current = this.head
var index = 0
while (index++ < position) {
current = current.next
}
current.data = newdata
return true
}
LinkedList.prototype.removeAt = function (position) {
if (position < 0 || position >= this.length) return false
var current = this.head
var previous = null
if (position == 0) {
this.head = this.head.next
this.length -= 1
return current.data
} else {
var index = 0
while (index++ < position) {
previous = current
current = current.next
}
previous.next = current.next
this.length -= 1
return current.data
}
}
LinkedList.prototype.remove = function (data) {
var position = this.indexOf(data)
return this.removeAt(position)
}
LinkedList.prototype.isEmpty = function () {
return this.length == 0
}
LinkedList.prototype.size = function () {
return this.length
}
双向链表
- 单向链表只能从头到尾遍历,但不能从这个节点回到上一个节点
- 双向链表既可以从头到尾也可以从尾到头
- 有向后的引用也有向前的引用
- 虽然占用内存稍微大点,但瑕不掩瑜