Skip to content

Instantly share code, notes, and snippets.

@itzjonas
Last active February 1, 2018 18:56
Show Gist options
  • Save itzjonas/321194189fbc9625e8fe2315d178e55d to your computer and use it in GitHub Desktop.
Save itzjonas/321194189fbc9625e8fe2315d178e55d to your computer and use it in GitHub Desktop.
Code Challenge: 2018-02-01
class LinkedList {
constructor(...values) {
this.head = null;
this.length = 0;
this.add(...values);
}
/**
* Individually adds a new node to the head of the linked list.
*
* @param value data to be added.
*/
_addToHead(value) {
const newNode = {
value,
next: this.head
};
this.head = newNode;
this.length++;
}
/**
* Adds to the head, in sequential order, an indefinite number of arguements.
*
* @param values data values to be individually added.
* @returns the full linked list.
*/
add(...values) {
values.forEach(value => this._addToHead(value));
return this;
}
/**
* Removes from the linked list the node at the head.
*
* @returns the data from the node removed.
*/
_removeFromHead() {
if (this.length === 0) {
return undefined;
}
const value = this.head.value;
this.head = this.head.next;
this.length--;
return value;
}
/**
* Removes a single node from the linked list with the value provided.
*
* @todo accept an indefinite number of values.
*
* @param value the data of the node to be removed.
* @returns undefined if not found; the data if at the head; or the full linked list.
*/
remove(value) {
if(this.length === 0) {
return undefined;
}
if (this.head.value === value) {
return this._removeFromHead();
}
let previousNode = this.head;
let thisNode = previousNode.next;
while(thisNode) {
if(thisNode.value === value) {
break;
}
previousNode = thisNode;
thisNode = thisNode.next;
}
if (thisNode === null) {
return undefined;
}
previousNode.next = thisNode.next;
this.length--;
return this;
}
/**
* Finds the node with the specific value provided.
*
* @param value the data of the node to be found.
* @returns the node where data was found.
*/
find(value) {
let thisNode = this.head;
while(thisNode) {
if(thisNode.value === value) {
return thisNode;
}
thisNode = thisNode.next;
}
return thisNode;
}
}
const myList = new LinkedList();
console.log('Adding values 4, 7 and 8 to the head:\n', JSON.stringify(myList.add(4, 7, 8), null, '\t'));
console.log('Finding node with value 7:\n', JSON.stringify(myList.find(7), null, '\t'));
console.log('Removing node with value 7:\n', JSON.stringify(myList.remove(7), null, '\t'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment