Created
February 14, 2016 16:27
-
-
Save snarisi/c0126c6c0da1c6103cb4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var LinkedList = function() { | |
} | |
LinkedList.prototype.addToTail = function(value) { | |
var newNode = new Node(value); | |
if (!this.tail && !this.head) { | |
this.tail = newNode; | |
this.head = newNode; | |
} else { | |
var newTail = newNode; | |
var oldTail = this.tail; | |
oldTail.next = newTail; | |
newTail.previous = oldTail; | |
this.tail = newTail; | |
} | |
} | |
LinkedList.prototype.addToHead = function(value) { | |
var newNode = new Node(value); | |
if (!this.head && !this.tail) { | |
this.head = newNode; | |
this.tail = newNode; | |
} else { | |
var oldHead = this.head; | |
oldHead.previous = newNode; | |
newNode.next = oldHead; | |
this.head = newNode; | |
} | |
} | |
LinkedList.prototype.removeHead = function() { | |
if (this.head) { | |
var headToRemove = this.head; | |
if (headToRemove.next) { | |
var headToPromote = headToRemove.next; | |
headToPromote.previous = null; | |
this.head = headToPromote; | |
} else { | |
this.head = undefined; | |
this.tail = undefined; | |
} | |
return headToRemove.value; | |
} | |
} | |
LinkedList.prototype.removeTail = function() { | |
if (this.tail) { | |
var tailToRemove = this.tail; | |
} if (tailToRemove.previous) { | |
var tailToPromote = tailToRemove.previous; | |
tailToPromote.next = null; | |
this.tail = tailToPromote; | |
} else { | |
this.tail = undefined; | |
this.head = undefined; | |
} | |
return tailToRemove.value; | |
} | |
LinkedList.prototype.search = function(value) { | |
var findValue = function(value, currentNode) { | |
//base case | |
//if the value is found, return the value | |
if (typeof value === 'function') { | |
if (value(currentNode.value)) { | |
return currentNode.value; | |
} | |
} else { | |
if (currentNode.value.valueOf() === value) { | |
return currentNode.value; | |
} | |
} | |
//edge case | |
//if .next = null return null | |
if (!currentNode.next) { | |
return null; | |
} | |
//recursive case | |
return findValue(value, currentNode.next); | |
} | |
return findValue(value, this.head); | |
} | |
var Node = function(value) { | |
this.value = value; | |
this.next = null; | |
this.previous = null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment