Skip to content

Instantly share code, notes, and snippets.

@Cfeusier
Created December 14, 2014 09:25
Show Gist options
  • Save Cfeusier/1806700d30ce178cb810 to your computer and use it in GitHub Desktop.
Save Cfeusier/1806700d30ce178cb810 to your computer and use it in GitHub Desktop.
Singly Linked List implementation in JavaScript
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