Last active
September 7, 2017 09:45
-
-
Save sue71/f93aca327211b9000545b7106c61adcb to your computer and use it in GitHub Desktop.
This file contains 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.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