Skip to content

Instantly share code, notes, and snippets.

@gregnb
Last active June 13, 2019 20:02
Show Gist options
  • Save gregnb/df26e5efdeeda77302a887a870559a1d to your computer and use it in GitHub Desktop.
Save gregnb/df26e5efdeeda77302a887a870559a1d to your computer and use it in GitHub Desktop.
ES6 Singly Linked List
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();
@seemcat
Copy link

seemcat commented Jun 13, 2019

Love the simplicity of this. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment