Create a gist now

Instantly share code, notes, and snippets.

Embed
class LinkedList {
constructor(...values) {
this.head = null;
this.tail = null;
this.size = 0;
if (values.length > 0) {
values.forEach(this.add.bind(this));
}
}
// Create new node
createNode(value) {
return {
value,
next: null
};
}
// Find first node by value
find(value) {
let node = this.head;
while (node) {
if (value === node.value) {
break;
}
node = node.next;
}
return node;
}
// Insert node at tail
add(value) {
const node = this.createNode(value)
if (!this.head) {
this.head = node;
this.tail = node;
} else {
this.tail.next = node;
this.tail = node;
}
this.size++;
}
// Remove node by value
remove(value) {
if (!this.head) {
return;
}
if (this.head.value === value) {
this.head = this.head.next
this.size--;
}
let previous = this.head;
let current = previous.next;
while (current) {
if (current.value === value) {
break;
}
previous = current
current = previous.next
}
if (!current) {
return;
}
if (!current.next) {
this.tail = current;
}
// Remove ref
previous.next = current.next
this.size--;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment