Skip to content

Instantly share code, notes, and snippets.

@rikkrome
Created August 7, 2018 19:33
Show Gist options
  • Save rikkrome/addf8278ef5b6a97ddd86328e404c64a to your computer and use it in GitHub Desktop.
Save rikkrome/addf8278ef5b6a97ddd86328e404c64a to your computer and use it in GitHub Desktop.
JS Linked list
{
function LinkedList() {
this.head = null;
this.tail = null;
}
function Node(value, next, prev) {
this.value = value;
this.next = next;
this.prev = prev;
}
LinkedList.prototype.addToHead = function(value) {
const newNode = new Node(value,this.head,null);
if (this.head)
this.head.prev = newNode;
else
this.tail = newNode;
this.head = newNode;
}
LinkedList.prototype.addToTail = function(value) {
const newNode = new Node(value,null,this.tail);
if (this.tail)
this.tail.next = newNode;
else
this.head = newNode;
this.tail = newNode;
}
LinkedList.prototype.removeHead = function() {
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;
}
LinkedList.prototype.search = function(searchValue) {
let currentNode = this.head;
while (currentNode) {
if (currentNode.value === searchValue)
return currentNode;
currentNode = currentNode.next;
}
return null;
}
const list = new LinkedList();
list.addToHead(100);
list.addToTail(200);
list.addToHead(300);
console.log(list.search(100)); // true
console.log(list.search(300)); // true
console.log(list.search(1)); // true
console.log(list);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment