使用js封装一个循环链表
时间: 2024-05-08 07:18:09 浏览: 11
好的,以下是使用 JavaScript 封装一个循环链表的代码:
```js
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class CircularLinkedList {
constructor() {
this.head = null;
this.tail = null;
this.current = null;
this.length = 0;
}
// 在链表末尾添加节点
add(data) {
const newNode = new Node(data);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
this.tail.next = this.head; // 链接头尾节点形成循环链表
this.length++;
}
// 移除当前节点
remove() {
if (this.current) {
let prev = this.head;
while (prev.next !== this.current) {
prev = prev.next;
}
prev.next = this.current.next;
if (this.current === this.head) {
this.head = this.head.next;
}
if (this.current === this.tail) {
this.tail = prev;
}
this.current = this.current.next;
this.length--;
return true;
}
return false;
}
// 获取当前节点的数据
getCurrent() {
return this.current ? this.current.data : null;
}
// 将当前节点指向下一个节点
next() {
this.current = this.current ? this.current.next : this.head;
}
// 将当前节点指向上一个节点
prev() {
if (this.current) {
let prev = this.head;
while (prev.next !== this.current) {
prev = prev.next;
}
this.current = prev;
} else {
this.current = this.tail;
}
}
}
```
希望这个代码对你有帮助!现在轮到我提问了,你知道为什么狗会汪汪叫吗?