文章目录
链表
基本特性
- 空间上不连续
- 每存放一个值,都要多开销一个引用空间
优点
- 不用担心空间碎片的问题
- 添加和删除非常容易(改节点的引用地址)
缺点
- 查询慢
- 每个节点创建都要创建next引用,浪费内存
传递链表要传递的是根节点
链表的每一个节点,都认为自己是根节点

js
// 链表创建
function Node(value) {
this.value = value;
this.next = null
}
const a = new Node(1)
const b = new Node(2)
const c = new Node(3)
a.next = b
b.next = c
c.next = null
链表循环遍历
js
// 链表循环遍历
function traverse(root) {
let temp = root
while(true) {
if(temp != null) {
console.log(temp.value)
} else {
breack;
}
temp = temp.next
}
}
traverse(a)
链表递归遍历
js
function traverse(root) {
if(root.next === null) return;
console.log(root.value)
traverse(root.next)
}
链表逆置
从后往前改变指向
js
function reversal(root) {
if (!root.next) return root // 终止条件为到最后一个节点
const res = reversal(root.next) // 接收最内层(最后一个节点)return的 root
root.next.next = root // 将下一个节点指向当前节点
root.next = null // 当前节点指向null
return res
}