Skip to content

Instantly share code, notes, and snippets.

@scopevale
Forked from TheIronDev/LinkedList.js
Last active August 29, 2015 14:07
Show Gist options
  • Save scopevale/5b70f27e8ba8b0c48d70 to your computer and use it in GitHub Desktop.
Save scopevale/5b70f27e8ba8b0c48d70 to your computer and use it in GitHub Desktop.
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) {
var 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) {
var 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) {
var 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