Skip to content

Instantly share code, notes, and snippets.

@aelshamy
Created December 27, 2016 08:15
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 aelshamy/3a2313745f4f0924729f6e1281b345c1 to your computer and use it in GitHub Desktop.
Save aelshamy/3a2313745f4f0924729f6e1281b345c1 to your computer and use it in GitHub Desktop.
LinkedList created by aelshamy - https://repl.it/ExG4/4
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){
var newNode = new Node(value, this.head, null);
//list is not empty;
if(this.head) this.head.prev = newNode;
//list is empty so make the head and tail is the new node;
else this.tail = newNode;
this.head = newNode;
}
LinkedList.prototype.addToTail = function(value){
var 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(){
//list is empty
if(!this.head) return null;
var val = this.head.value;
//move current head to the next;
this.head = this.head.next;
//list has more than one item ?
if(this.head) this.head.prev = null;
else this.tail = null;
return val;
}
LinkedList.prototype.removeTail = function(){
if(!this.tail) return null;
var val = this.tail.value;
this.tail = this.tail.prev;
if(this.tail) this.tail.next = null;
else this.head = null;
return val;
}
LinkedList.prototype.search = function(searchValue){
var currentNode = this.head;
while(currentNode){
if (currentNode.value == searchValue) return currentNode.value;
currentNode = currentNode.next;
}
return null;
}
LinkedList.prototype.indexOf = function(value){
var currentNode = this.head;
var indexes = [];
var currentIndex = 0;
while(currentNode){
if (currentNode.value == value) indexes.push(currentIndex) ;
currentNode = currentNode.next;
currentIndex++;
}
return indexes;
}
var ll = new LinkedList();
ll.addToHead(123);
ll.addToHead(70);
ll.addToTail('Hello');
ll.addToTail(19);
ll.addToTail('world');
ll.addToTail(20);
ll.addToTail(3000);
console.log(ll.indexOf(20));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment