Skip to content

Instantly share code, notes, and snippets.

@gitfaf
Created September 12, 2017 13:18
Show Gist options
  • Save gitfaf/3da3a52e1e23443f35f02bb38778e3f7 to your computer and use it in GitHub Desktop.
Save gitfaf/3da3a52e1e23443f35f02bb38778e3f7 to your computer and use it in GitHub Desktop.
Simple linked list in JavaScript
/* Linked List in EcmaScript */
class Node {
constructor (value, next = null) {
this.value = value;
this.next = next;
}
}
class LinkedList {
constructor (node) {
this.root = node;
}
append (value) {
let tmp = this.root;
while(tmp.next) {
tmp = tmp.next; // I wish there was tmp .= next;
}
tmp.next = new Node(value);
}
prepend (value) {
let newNode = new Node(value);
newNode.next = this.root;
this.root = newNode;
}
print () {
let tmp = this.root;
while(tmp) {
console.log(tmp.value);
tmp = tmp.next;
}
}
toString () {
let tmp = this.root;
let out = '';
while(tmp) {
out += ` -> ${tmp.value}`;
tmp = tmp.next;
}
out += ' -> null';
return out;
}
sum () {
let tmp = this.root;
let out = 0;
while(tmp) {
out += tmp.value;
tmp = tmp.next;
}
return out;
}
}
class Run {
static simpleCase () {
let root = new Node(1);
let list = new LinkedList(root);
console.log(list.toString());
list.append(2);
console.log(list.toString());
list.append(3);
console.log(list.toString());
list.append(4);
console.log(list.toString());
list.prepend(0);
console.log(list.toString());
list.print();
console.log(list.toString());
console.log(list.sum());
}
}
Run.simpleCase();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment