Created
January 9, 2019 06:37
-
-
Save 197291/309d934a02d6c33c05d7a3fb39ccd508 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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