Skip to content

Instantly share code, notes, and snippets.

@bflannery
Last active January 24, 2019 19:11
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 bflannery/41236acb3d73c40e4bb65d9fc2ac5521 to your computer and use it in GitHub Desktop.
Save bflannery/41236acb3d73c40e4bb65d9fc2ac5521 to your computer and use it in GitHub Desktop.
ES6 Linked List
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
addToHead(value) {
let newNode = new Node(value, this.head, null);
if (this.head) this.head.prev = newNode;
else this.tail = newNode;
this.head = newNode;
}
addToTail(value) {
let newNode = new Node(value, null, this.tail)
if (this.tail) this.tail.next = newNode;
else this.head = newNode;
this.tail = newNode;
}
removeHead() {
if (!this.head) return null;
let value = this.head.value;
this.head = this.head.next;
if(this.head) this.head.prev = null;
else this.tail = null;
return value;
}
removeTail() {
if (!this.tail) return null;
let value = this.tail.value;
this.tail = this.tail.prev;
if (this.tail) this.tail.prev = null;
else this.head = null;
return value;
}
search(searchValue) {
let currentNode = this.head;
while (currentNode) {
if (currentNode.value === searchValue) {
return currentNode.value;
}
currentNode = currentNode.next
}
return null;
}
indexOf(value) {
let indexes = [];
let i = 0;
let currentNode = this.head;
while (currentNode) {
if(currentNode.value === value) indexes.push(i)
currentNode = currentNode.next
i++
}
return indexes;
}
};
class Node {
constructor(value, next, prev) {
this.value = value;
this.next = next;
this.prev = prev;
}
};
var ll = new LinkedList();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment