Skip to content

Instantly share code, notes, and snippets.

@jharris-code
Last active January 14, 2019 18:51
Show Gist options
  • Save jharris-code/e995462d0f7240363ad62300803fa667 to your computer and use it in GitHub Desktop.
Save jharris-code/e995462d0f7240363ad62300803fa667 to your computer and use it in GitHub Desktop.
JavaScript Linked List Implementation
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
add(data) {
let n = new Node(data);
if(!this.head) {
this.head = n;
this.tail = n;
} else {
this.tail.next = n;
this.tail = n;
return n;
}
}
delete(node) {
let n = this.head;
if(node === this.head){
if(this.head === this.tail) {
this.head = null;
this.tail = null;
} else {
this.head = this.head.next;
return;
}
}
while(n.next) {
if(n.next === node) {
if(n.next === this.tail) {
this.tail = n;
}
n.next = n.next.next;
return;
}
n = n.next;
}
}
}
//Sample Usage:
let ll = new LinkedList();
let a = ll.add('a');
let b = ll.add('b');
let c = ll.add('c');
let d = ll.add('d');
console.log(ll.tail);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment