Skip to content

Instantly share code, notes, and snippets.

@TheIronDev
Last active December 23, 2015 07:59
Show Gist options
  • Save TheIronDev/6604756 to your computer and use it in GitHub Desktop.
Save TheIronDev/6604756 to your computer and use it in GitHub Desktop.
Linked List Algorithm tests
var Node = function(value) {
this.value = value;
this.next=null;
return this;
};
var LinkedList = function(node){
this.head = node;
return this;
};
LinkedList.prototype.insertEnd = function(newNode, currentNode) {
currentNode = currentNode || this.head;
if(currentNode.next !== null) {
return this.insertEnd(newNode, currentNode.next);
} else {
currentNode.next = newNode;
}
};
LinkedList.prototype.insertBeginning = function(newNode) {
newNode.next = this.head;
this.head = newNode;
};
LinkedList.prototype.search = function(searchValue, currentNode) {
currentNode = currentNode || this.head;
if(currentNode.value == searchValue) {
console.log("true");
return true;
} else if(currentNode.next !== null) {
return this.search(searchValue, currentNode.next);
}
console.log("not found");
return false;
};
LinkedList.prototype.remove = function(deleteValue, currentNode, parentNode) {
currentNode = currentNode || this.head;
if(currentNode.value === deleteValue) {
if(currentNode.next !== null) {
parentNode.next = currentNode.next;
} else {
parentNode.next = null;
}
} else if(currentNode.next !== null) {
return this.remove(deleteValue, currentNode.next, currentNode);
}
};
// Improvements from: http://codereview.stackexchange.com/a/31522/29315
LinkedList.prototype.search = function(searchValue, currentNode) {
currentNode = currentNode || this.head;
if(currentNode.value == searchValue) {
console.log("true");
return true;
} else if(currentNode.next !== null) {
return this.search(searchValue, currentNode.next);
}
console.log("not found");
return false;
};
(function(){
// LinkedList Example
var linkedList = new LinkedList(new Node("oldHead"));
linkedList.insertEnd(new Node(2));
linkedList.insertEnd(new Node("cat"));
linkedList.insertEnd(new Node("dog"));
linkedList.insertEnd(new Node(100));
linkedList.search("cat");
console.log('size: '+linkedList.size());
linkedList.remove("cat");
console.log('size: '+linkedList.size());
linkedList.search("cat");
console.log("current head: "+linkedList.head.value);
linkedList.insertBeginning(new Node("testBeginningInsert"));
console.log("current head: "+linkedList.head.value);
console.log('size: '+linkedList.size());
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment