js版数据结构_04链表(3)
本篇博文知识点
- 循环链表(由于上篇是双向链表故这里以双向循环链表为例)
1. 循环链表
上篇总结了双向链表,而循环链表则是对链表的进一步改进。使得它们可以头连尾,尾连头。构成一个闭环。
同样,它的很多操作是和单链表是一样的。在这我们只看它们任意位置插入和任意位置删除两个方法
insertX(e, index):
insertX(e, index) {
// 判断是否越界
if (index >= 0 && index <= this.count) {
let node = new DoubleLNode(e);
// 首部
if (index === 0) {
if (this.head == null) {
this.head = node;
this.q = node;
node.next = node;
node.pre = node;
} else {
node.next = this.head;
this.head.pre = node;
node.pre = this.q;
this.head = node;
}
// 尾部
} else if (index === this.count) {
this.q.next = node;
node.next = this.head;
node.pre = this.q;
this.head.pre = node;
this.q = node;
// 中间不变,没有头尾的操作
} else {
let currentPre = this.getElementAt(index - 1);
let current = currentPre.next;
currentPre.next = node;
node.pre = currentPre;
node.next = current;
current.pre = node;
}
this.count++;
return true;
}
return false;
}
先来看一下效果:
//简单测试:
let test = new DoubleLinkedList();
test.insertX(1, 0);
test.insertX(2, 1);
test.insertX(3, 2);
console.log(test);
效果图:
removeAtX(index): (ps:下面这个写完眼镜检查了一下没有做测试,偷了下懒。如果有错希望可以提醒下我,今天想早睡一点~~)
removeAtX(index) {
// 是否越界
if (index <= 0 && index < this.count) {
// 头
if (index === 0) {
if (this.count === 1) {
this.head = null;
this.q = null
} else {
this.head = this.head.next;
this.q.next = this.head;
this.head.pre = this.q;
}
// 尾
} else if (index === this.count - 1) {
this.q = this.q.pre;
this.q.next = this.head;
this.head.pre = this.q;
// 中
} else {
let currentPre = this.getElementAt(index - 1);
let currentNext = currentPre.next.next;
currentPre.next = currentPre;
currentNext.pre = currentPre;
}
}
}