Skip to content

Instantly share code, notes, and snippets.

@197291
Created January 9, 2019 06:37
Show Gist options
  • Save 197291/309d934a02d6c33c05d7a3fb39ccd508 to your computer and use it in GitHub Desktop.
Save 197291/309d934a02d6c33c05d7a3fb39ccd508 to your computer and use it in GitHub Desktop.
class LinkedList {
constructor(...values) {
this.head = null;
this.length = 0;
this.addToHead(...values);
}
_addSingleItemToHead(value) {
const newNode = { value };
newNode.next = this.head;
this.head = newNode;
this.length++;
}
addToHead(...values) {
values.forEach(value => this._addSingleItemToHead(value));
return this;
}
removeFromHead() {
if (this.length === 0) {
return undefined;
}
const value = this.head.value;
this.head = this.head.next;
this.length--;
return value;
}
find(val) {
let thisNode = this.head;
while(thisNode) {
if(thisNode.value === val) {
return thisNode;
}
thisNode = thisNode.next;
}
return thisNode;
}
remove(val) {
if(this.length === 0) {
return undefined;
}
if (this.head.value === val) {
return this.removeFromHead();
}
let previousNode = this.head;
let thisNode = previousNode.next;
while(thisNode) {
if(thisNode.value === val) {
break;
}
previousNode = thisNode;
thisNode = thisNode.next;
}
if (thisNode === null) {
return undefined;
}
previousNode.next = thisNode.next;
this.length--;
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment