class CircularLinkedList {
constructor(init = []) {
this.size = init.length;
this.nodes = [];
this.head = this.size > 0 ? init[0] : null;
init.forEach((v, i) => {
this.nodes[v] = {
prev: init[(i - 1 + this.size) % this.size],
next: init[(i + 1) % this.size]
};
});
}
next(n) {
return this.nodes[n] !== undefined ? this.nodes[n].next : null;
}
move(n, m) {
if (this.nodes[n] !== undefined && this.nodes[m] !== undefined) {
if (n === this.head) {
this.head = this.nodes[n].next;
}
this.nodes[this.nodes[n].prev].next = this.nodes[n].next;
this.nodes[this.nodes[n].next].prev = this.nodes[n].prev;
this.nodes[n].prev = m;
this.nodes[n].next = this.nodes[m].next;
this.nodes[m].next = n;
this.nodes[this.nodes[this.nodes[m].next].next].prev = n;
}
}
*[Symbol.iterator]() {
if (this.size > 0) {
let current = this.head;
while (this.nodes[current].next !== this.head) {
yield current;
current = this.nodes[current].next;
}
yield current;
}
}
}