JavaScript中的链表
- 要储存多个元素,除了数组还可以选择链表
- 链表在内存中不必是连续的空间
- 链表的每个元素由一个存储元素本身的节点和一个指向下一个元素的引用(有些语言称为指针或者链接)组成
- 链表优点:
- 内存空间不是比是连续的. 可以充分利用计算机的内存. 实现灵活的内存动态管理
- 链表不必在创建时就确定大小, 并且大小可以无限的延伸下去
- 链表在插入和删除数据时, 时间复杂度可以达到O(1). 相对数组效率高很多
- 链表缺点
- 链表访问任何一个位置的元素时, 都需要从头开始访问(无法跳过第一个元素访问任何一个元素)
- 无法通过下标直接访问元素, 需要从头一个个访问, 直到找到对应的问题
链表实现
链表常见的操作
append(element)
:向列表尾部添加一个新的项insert(position, element)
:向列表的特定位置插入一个新的项remove(element)
:从列表中移除一项indexOf(element)
:返回元素在列表中的索引。如果列表中没有该元素则返回-1
removeAt(position)
:从列表的特定位置移除一项isEmpty()
:如果链表中不包含任何元素,返回true
,如果链表长度大于0则返回false
size()
:返回链表包含的元素个数。与数组的length
属性类似toString()
:由于列表项使用了Node
类,就需要重写继承自JavaScript对象默认的toString
方法,让其只输出元素的值
function LinkedList() {
function Node(element) {
this.element = element
this.next = null
}
this.length = 0
this.head = null
LinkedList.prototype.append = function (element) {
var newNode = new Node(element)
if (this.head === null) {
this.head = newNode
} else {
var current = this.head
while (current.next) {
current = current.next
}
current.next = newNode
}
this.length++
}
LinkedList.prototype.toString = function () {
var current = this.head
var listString = ""
while (current) {
listString += "," + current.element
current = current.next
}
return listString.slice(1)
}
LinkedList.prototype.insert = function (position, element) {
if (position < 0 || position > this.length) return false
var newNode = new Node(element)
var current = this.head
var previous = null
index = 0
if (position == 0) {
newNode.next = current
this.head = newNode
} else {
while (index++ < position) {
previous = current
current = current.next
}
newNode.next = current
previous.next = newNode
}
this.length++
return true
}
LinkedList.prototype.removeAt = function (position) {
if (position < 0 || position >= this.length) return null
var current = this.head
var previous = null
var index = 0
if (position === 0) {
this.head = current.next
} else {
while (index++ < position) {
previous = current
current = current.next
}
previous.next = current.next
}
this.length--
return current.element
}
LinkedList.prototype.indexOf = function (element) {
var current = this.head
index = 0
while (current) {
if (current.element === element) {
return index
}
index++
current = current.next
}
return -1
}
LinkedList.prototype.remove = function (element) {
var index = this.indexOf(element)
return this.removeAt(index)
}
LinkedList.prototype.isEmpty = function () {
return this.length == 0
}
LinkedList.prototype.size = function () {
return this.length
}
LinkedList.prototype.getFirst = function () {
return this.head.element
}
}