链表像是一个火车,每一个 node 就像是一节火车厢,它不仅要携带自己的信息 (item),还要与下一节火车厢相连(next)
next指向下一个节点,下一个节点的内容
(一)链表的操作
1. 插入元素 insert
2. 尾部添加元素 append
3. 获取元素索引 indexOf
4. 从链表中移除一项~remove(element) 移除 element
5. 从链表中特定 位置 移除一项~ removeAt(position) 移除position所在的项
(二)代码实现
一个连接着一个
<script>
// 定义链表类
var LinkedList = function () {
var head = null // 初始化链表头为空
var length = 0 // 初始化链表长度为0
// 链表的每一个节点 包括本身以及下一个
var Node = function (elememt) {
this.elememt = elememt
this.next = null
}
// 链表尾添加元素
this.append = function (element) {
var node = new Node(element)
// 如果该链表没有头 那么传进来的第一项就是头
if (head === null) {
head = node
} else {
// 如果链表有头,那就把这一项放到链表末尾
// 一个节点的next如果是null 说明这项是链表末尾
// 从头开始查找末尾项
var current = head
// 有下一个节点说明不是末尾项 直到 current.next 是null 退出循环,此时current是末尾项
while (current.next) {
current = current.next
}
current.next = node // 添加到最后
}
length++ // 链表长度加一
}
// 在链表某一位置插入元素
this.insert = function (position, element) {
if (position < 0 || position > length - 1) {
return
}
if (position === 0) {
// 说明要替换头
var current = head
head = new Node(element)
head.next = current // 插入的元素的next指向之前的头
} else {
var index = 0
var current = head
var insertNode = new Node(element)
// 循环查找要插入的位置
while (index < position - 1) { // index 从 0 开始 减一
current = current.next
index++
}
// 找到位置 其后插入元素
var nextNode = current.next
current.next = insertNode
insertNode.next = nextNode
}
length++
}
// 获取元素的索引
this.getIndex = function (elememt) {
var index = 0;
var current = head
while (index < length) {
if (elememt === current.elememt) {
return index
} else {
current = current.next
index++
}
}
// 没找到 返回 -1
return -1
}
// 移除某一位置的元素
this.removeAt = function (position) {
if (position < 0 || position > length - 1) {
return
}
if (position === 0) {
// 换头
head = head.next
} else {
var index = 0
var current = head
while(index < position - 1) {
current = current.next
index++
}
current.next = current.next.next
}
length--
}
// 获取链表
this.getHead = function () {
return head
}
this.removeElement = function (element) {
// 代码复用 找 index 删除
var index = this.getIndex(element)
this.removeAt(index)
}
// 链表长度
this.size = function () {
return length
}
this.isEmpty = function () {
return length === 0
}
}
var link = new LinkedList()
link.append(1)
link.append(2)
link.append(3)
link.insert(2, 5) // 5是第三项 从0开始数数
link.removeAt(3)
link.removeElement(1)
console.log(link.getHead())
console.log(link.size())
console.log(link.isEmpty())
console.log(link.getIndex(5))
// console.log(link.getHead())
</script>
双向链表:
循环链表: