Last active
June 13, 2019 20:02
-
-
Save gregnb/df26e5efdeeda77302a887a870559a1d to your computer and use it in GitHub Desktop.
ES6 Singly Linked List
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 Node { | |
constructor(data) { | |
this.next = null; | |
this.data = data; | |
} | |
} | |
class LinkedList { | |
constructor() { | |
this.list = {}; | |
this.head = null; | |
this.tail = null; | |
} | |
add(data) { | |
let newNode = new Node(data); | |
/* no head. means there's no tail either so set it */ | |
if (!this.head) { | |
this.head = newNode; | |
this.tail = newNode; | |
} else { | |
/* add it to the end of the list. then set tail to newNode */ | |
this.tail.next = newNode; | |
this.tail = newNode; | |
} | |
} | |
find(data) { | |
let list = this.head; | |
let prev = null; | |
while (list !== null) { | |
if (list.data == data) { | |
return { prev: prev, current: list }; | |
} | |
prev = list; | |
list = list.next; | |
} | |
return null; | |
} | |
remove(data) { | |
let node = this.find(data); | |
if (node) { | |
node.prev.next = node.current.next; | |
} | |
} | |
print() { | |
let current = this.head; | |
while (current) { | |
current = current.next; | |
} | |
} | |
} | |
let List = new LinkedList(); | |
/* add nodes */ | |
List.add('item #1'); | |
List.add('item #2'); | |
List.add('item #3'); | |
List.add('item #4'); | |
List.add('item #5'); | |
/* print list */ | |
List.print(); | |
/* remove item */ | |
List.remove('item #4'); | |
List.print(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Love the simplicity of this. Thanks!