Skip to content

Instantly share code, notes, and snippets.

@connor11528
Created April 10, 2015 03:05
Show Gist options
  • Save connor11528/d0414c307c16e96807d1 to your computer and use it in GitHub Desktop.
Save connor11528/d0414c307c16e96807d1 to your computer and use it in GitHub Desktop.
linked list javascript implementation
var Node = function(value){
var node = {};
node.value = value;
node.next = null;
return node;
};
var LinkedList = function(){
var list = {};
list.head = null;
list.tail = null;
var listItems = {};
list.listItems = listItems;
var itemCount = 0;
list.addToTail = function(value){
var newNode = new Node();
newNode.value = value;
listItems[itemCount] = newNode;
list.tail = newNode;
// for adding first Node
if(list.head == null){
list.head = newNode;
} else {
listItems[itemCount-1].next = itemCount;
}
itemCount++;
};
list.removeHead = function(){
delete listItems[0];
for(var i = 0; i < itemCount; i++){
if(i == itemCount - 1){
break;
} else {
listItems[i] = listItems[i+1];
if(listItems[i].next !== null){
listItems[i].next -= 1;
}
delete listItems[i+1];
}
}
itemCount--;
list.head = listItems[0];
list.tail = listItems[itemCount-1];
};
list.contains = function(target){
for(var i = 0; i < itemCount; i++){
// if target string is equal to value property of a Node
if(listItems[i].value === target){
return true;
}
}
return false;
};
return list;
};
// Tests
// ======
var myList = new LinkedList();
myList.addToTail('item one');
myList.removeHead();
myList.addToTail('item two');
myList.addToTail('item three');
myList.addToTail('item four');
console.log(myList);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment