LinkedList = {
class LinkedList {
static of(...nodes) {
const list = new LinkedList;
for (const node of nodes) list.insert(node);
return list;
}
constructor() {
this.head = null;
}
*[Symbol.iterator]() {
let node = this.head;
while (node) {
yield node;
node = node.next;
}
}
insert(node, where = null) {
node.next = where;
let prev = null, next = this.head;
while (next !== where) prev = next, next = next.next;
if (prev) prev.next = node;
else this.head = node;
return this;
}
remove(node) {
let prev = null, next = this.head;
while (next !== node) prev = next, next = next.next;
if (prev) prev.next = node.next;
else this.head = node.next;
node.next = null;
return this;
}
reverse() {
let node = this.head;
if (!node) return this;
let prev = null;
let next = node.next;
while (next) {
node.next = prev;
prev = node;
node = next;
next = next.next;
}
node.next = prev;
this.head = node;
return this;
}
}
LinkedList.Node = class Node {
constructor(value) {
this.value = value;
this.next = null;
}
};
return LinkedList;
}