Published
Edited
Jun 9, 2022
Insert cell
Insert cell
Insert cell
class LinkedList {
constructor() {
this.head = null;
}

add(value) {
// if node is null
if (!this.head) {
this.head = new Node(value);
return;
}

let node = this.head;

while (node.next) {
node = node.next;
}

node.next = new Node(value);
}

delete(target) {
if (this.head.value === target) {
this.head = this.head.next;
return;
}

let node = this.head;
let prev = null;

while (node) {
if (node.value === target && prev) {
prev.next = node.next;
}
prev = node;
node = node.next;
}
}

print() {
let node = this.head;
let linkList = "";

while (node) {
linkList += `${node.value} -> `;
node = node.next;
}

return linkList;
}

has(target) {
let node = this.head;

while (node) {
if (node.value === target) return true;
node = node.next;
}

return false;
}
reverse() {
let previous = null;
let node = this.head;

while (node) {
const temp = node.next;
node.next = previous;
previous = node;
node = temp;
}

this.head = previous;
}
}
Insert cell
list = new LinkedList()
Insert cell
list.add("a")
Insert cell
list.add("b")

Insert cell
list.add("c")
Insert cell
list.print()
Insert cell
list.reverse()
Insert cell
list.print()
Insert cell
list.delete("b")
Insert cell
list.print()
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