Skip to content

Instantly share code, notes, and snippets.

@BideoWego
Created November 21, 2018 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BideoWego/cf284542c0471edff65ad8836134346b to your computer and use it in GitHub Desktop.
Save BideoWego/cf284542c0471edff65ad8836134346b to your computer and use it in GitHub Desktop.
Simple linked list implementation in javascript
class Node {
constructor(value, next) {
this.value = value;
this.next = next;
}
}
class LinkedList {
constructor() {
this.head = null;
}
add(value) {
if (!this.head) {
return this.head = new Node(value);
}
var node = this.head;
while (node.next) {
node = node.next;
}
var n = node.next = new Node(value);
return n;
}
remove(node) {
if (node === this.head) {
return this.head = this.head.next;
}
var current = this.head;
var last = null;
while (current) {
if (node === current) {
last.next = current.next;
}
last = current;
current = current.next;
}
return node;
}
}
var ll = new LinkedList();
ll.add(1);
console.log(ll);
// LinkedList { head: Node { value: 1, next: undefined } }
var node = ll.add(2);
console.log(ll);
// LinkedList {
// head: Node { value: 1, next: Node { value: 2, next: undefined } } }
ll.add(3);
console.log(ll);
// LinkedList {
// head: Node { value: 1, next: Node { value: 2, next: [Node] } } }
ll.remove(node);
console.log(ll);
// LinkedList {
// head: Node { value: 1, next: Node { value: 3, next: undefined } } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment