Skip to content

Instantly share code, notes, and snippets.

@jpoechill
Created June 5, 2017 05:11
Show Gist options
  • Save jpoechill/f9e89b288d87b14ea54d2db38baf5d56 to your computer and use it in GitHub Desktop.
Save jpoechill/f9e89b288d87b14ea54d2db38baf5d56 to your computer and use it in GitHub Desktop.
Customized Linked Lists with Javascript
// From ThatJSDude
function linkedList () {
this.head = null
this.length = 0
}
linkedList.prototype.push = function (val) {
var node = {
value: val,
next: null
}
if (!this.head) {
this.head = node
this.length++;
} else {
var current = this.head
while (current.next) {
current = current.next
}
current.next = node
this.length++;
}
}
linkedList.prototype.removeNode = function (position) {
var currentNode = this.head,
length = this.length,
count = 0,
message = {failue: 'Failure: non-existent node in this list.'},
beforeNodeToDelete = null,
nodeToDelete = null,
deletedNode = null;
if (position < 0 || position > this.length) {
throw new Error(message.failure)
}
if (position === 1) {
this.head = currentNode.next
deletedNode = currentNode
currentNode = null
this.length--
return deletedNode
}
while (count < position) {
beforeNodeToDelete = currentNode
nodeToDelete = currentNode.next
count++
}
beforeNodeToDelete.next = nodeToDelete
deletedNode = nodeToDelete
nodeToDelete = null
this.length--
return deletedNode
}
linkedList.prototype.searchAt = function (position) {
var currentNode = this.head,
count = 1,
message = {failure: 'Failure: non-existent node in this list.'};
if (this.length === 0 || position < 1 || position > this.length) {
// console.log("Error occurred.");
throw new Error(message.failure);
}
while (count < position) {
currentNode = currentNode.next
count++
}
console.log(currentNode.value);
return currentNode;
}
var myLinkedList = new linkedList()
myLinkedList.push("ABCD")
myLinkedList.push("1234")
console.log(myLinkedList.removeNode(1).value)
// myLinkedList.searchAt(2)
// console.log(myLinkedList.head)
// console.log(myLinkedList.head.next)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment