Skip to content

Instantly share code, notes, and snippets.

@nikoheikkila
Last active September 13, 2018 14:04
Show Gist options
  • Save nikoheikkila/2c5aa9e35101fdc14bfca0fc0cf89adc to your computer and use it in GitHub Desktop.
Save nikoheikkila/2c5aa9e35101fdc14bfca0fc0cf89adc to your computer and use it in GitHub Desktop.
Linked lists in Javascript
/**
* Linked lists in Javascript
* @see https://dev.to/ryanfarney3/intro-to-linked-lists-in-js-19b4
*/
class Node {
constructor(data, next = null) {
this.data = data;
this.next = next;
}
}
class LinkedList {
constructor(data = null) {
this.head = data;
}
first() {
return this.head;
}
last() {
let node = this.head;
if (!node) return null;
while (node) {
if (node.next === null) return node;
node = node.next;
}
}
prepend(data) {
this.head = new Node(data, this.head);
}
reset() {
this.head = null;
}
removeFirst() {
if (!this.head) return;
this.head = this.head.next;
}
removeLast() {
if (!this.head) return;
if (!this.head.next) return this.head = null;
let prev = this.head;
while (prev) {
let node = prev.next;
if (!node.next) return prev.next = null;
prev = prev.next;
}
}
push(data) {
const node = new Node(data);
const last = this.last();
if (last) {
last.next = node;
} else {
this.head = node;
}
}
count() {
let counter = 0;
let node = this.head;
while (node) {
counter++;
node = node.next;
}
return counter;
}
isEmpty() {
return this.count() === 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment