鏈表像是一個火車,每一個 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>
雙向鏈表:
循環鏈表: