链表是一个线性结构,同时也是一个天然的递归结构。链表结构可以充分利用计算机内存空间,实现灵活的内存动态管理。
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5807527b9304dd781c1e9508c5be4822.jpeg#pic_center)
链表的增删改查
<script>
class Node {
constructor(v, next) {
this.value = v;
this.next = next;
}
}
class LinkList {
constructor() {
this.size = 0;
this.virtualHeader = new Node(null, null);
}
checkIndex(index) {
if (index < 0 || index > this.size) throw new Error("Index Error!");
}
_find(header, index, currentIndex) {
if (index === currentIndex) return header;
return this._find(header.next, index, currentIndex + 1);
}
addNode(val, index) {
this.checkIndex(index);
let prev = this._find(this.virtualHeader, index, 0);
prev.next = new Node(v, prev.next);
this.size++;
return prev.next;
}
addToFirst(val) {
this.addNode(val, 0);
}
addToLast(val) {
this.addNode(val, this.getSize());
}
insertNode(val, index) {
this.addNode(val, index);
}
delNode(index, isLast) {
this.checkIndex(index);
index = isLast ? index - 1 : index;
let prev = this._find(this.virtualHeader, index, 0);
let node = prev.next;
prev.next = node.next;
node.next = null;
this.size--;
return node;
}
delFirstNode() {
return this.delNode(0);
}
delLastNode() {
return this.delNode(this.size, true);
}
getNode(index) {
this.checkIndex(index);
if (this.isEmpty()) return;
return this._find(this.virtualHeader, index, 0).next;
}
isEmpty() {
return this.getSize() === 0;
}
getSize() {
return this.size;
}
}
</script>