Created
December 14, 2014 09:25
-
-
Save Cfeusier/1806700d30ce178cb810 to your computer and use it in GitHub Desktop.
Singly Linked List implementation in JavaScript
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 Node = function(value) { | |
var node = {}; | |
node.value = value; | |
node.next = null; | |
return node; | |
}; | |
var LinkedList = function() { | |
var list = {}; | |
list.head = null; | |
list.tail = null; | |
list.addToTail = function(value) { | |
var node = Node(value); | |
if (!list.head) { | |
list.head = node; | |
list.tail = node; | |
} else { | |
list.tail.next = node; | |
list.tail = node; | |
} | |
}; | |
list.removeHead = function() { | |
var oldHead = list.head; | |
list.head = oldHead.next; | |
return oldHead.value; | |
}; | |
list.contains = function(target) { | |
var current = list.head; | |
while (current) { | |
if (current.value === target) return true; | |
current = current.next; | |
} | |
return false; | |
}; | |
return list; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment