Skip to content

Instantly share code, notes, and snippets.

@sue71
Last active September 7, 2017 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sue71/f93aca327211b9000545b7106c61adcb to your computer and use it in GitHub Desktop.
Save sue71/f93aca327211b9000545b7106c61adcb to your computer and use it in GitHub Desktop.
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