Public
Edited
Mar 25
Paused
2 forks
Importers
Insert cell
Insert cell
class LinkedList extends Array {
// Constructor
constructor(...values) {
super(...values);
}
// True iff list is empty
empty() {
return this.length == 0;
}
// Adds x to the head of the list
add(x) {
if (this.empty()) this.push(x, new LinkedList());
else [this[0], this[1]] = [x, new LinkedList(...this)];
}
// Removes an element from the head of the list
remove() {
let nxt = this.next();
if (nxt.empty()) {
this.splice(0, 2);
} else [this[0], this[1]] = [nxt[0], nxt[1]];
}
// Value at the head of the list
value() {
return this[0];
}
// List without its head
next() {
return this[1];
}
// Returns the LinkedList point where x appears
find(x) {
let node = this;
while (!node.empty() && node.value() != x) node = node.next();
if (node.empty()) return null;
return node;
}
}
Insert cell
Insert cell
{
let l = new LinkedList();
l.add(1);
l.add(2);
l.add(3);
return l.find(2);
}
Insert cell
{
function mystery(L, y) {
if (L.empty()) return L.add(y);
if (L.value() == y) L.remove();
mystery(L.next(), y);
}
let l = new LinkedList();
for (let x of [1, 2, 1, 3, 1, 2, 3, 1, 2]) mystery(l, x);
return toArray(l);
}

// {
// let l = new LinkedList();
// for (let x of [1, 2, 3, 4, 5]) l.add(x);
// for (let y of [2, 3]) l.remove();
// return toArray(l);
// }

// {
// let l = new LinkedList();
// l.add(1);
// l.add(3);
// l.add(2);
// l.add(4);
// return l.remove();
// }
Insert cell
Insert cell
function orderedInsert(L, x) {
while (!L.empty() && L.value() < x) L = L.next();
L.add(x);
}
Insert cell
demoInsert = {
let L = new LinkedList();
for (let x of [7, 1, 5, 2]) orderedInsert(L, x);
return L;
}
Insert cell
toArray(demoInsert)
Insert cell
Insert cell
function toArray(L) {
let a = [];
while (!L.empty()) {
a.push(L.value());
L = L.next();
}
return a;
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more