JSFiddle - React, Tailwind, and code Playground
by Abdul Ahmad
JavaScript
class LinkedList {
_firstNode;
_lastNode;
_nodes = {
};
// - insert adds to the end
// - new inserts never have a 'next'
// - we add next to the 'last' node
insert(node) {
if (this._lastNode) {
node.last = this._lastNode;
this._lastNode.next = node;
}
if (!this._firstNode) {
this._firstNode = node;
}
this._lastNode = node;
this._nodes[node.val] = node;
this.logNodesInOrder();
}
makeFirst(nodeName) {
const node = this._nodes[nodeName];
if (this._firstNode === node) return;
// - update next/prev nodes first
const last = node.last;
const next = node.next;
if (node.last) node.last.next = next;
if (node.next) node.next.last = last;
const first = this._firstNode;
node.next = this._firstNode;
node.last = undefined;
first.last = node;
this._firstNode = node;
this.logNodesInOrder();
}
logNodesInOrder() {
let node = this._firstNode;
let max = 100;
let curr = 0;
while (curr < max) {
curr++;
console.log(node);
node = node.next;
}
}
}
class Node {
_val;
_last;
_next;
constructor(v) {
this._val = v;
}
get val() {
return this._val;
}
set last(val) {
this._last = val;
}
set next(val) {
this._next = val;
}
}
const nodes = ['a', 'b', 'c', 'd', 'e'];
const list = new LinkedList();
nodes.forEach(n => list.insert(new Node(n)));
list.makeFirst('c');