Singly Linked List from Cho
JavaScript
var makeLinkedList = function() {
/*
* Creates an object with its
* prototype referencing
* methodsOfLinkedList
*/
var instanceOfLinkedList = Object.create(methodsOfLinkedList);
/*
* Sets the initial head of a
* list to null
*/
instanceOfLinkedList.head = null;
/*
* Sets the initial tail of a
* list to null
*/
instanceOfLinkedList.tail = null;
/*
* Returns an instance of a
* linked list
*/
return instanceOfLinkedList;
};
var methodsOfLinkedList = {
add: function(value) {
/*
* Creates a new instance of a
* node.
*/
var newNode = makeNode(value);
/*
* If the list is empty,
* then assign the new node
* as the head of the list.
*/
if (!this.head) {
this.head = newNode;
}
/*
* If the list contains a
* tail, then assign the new
* node as the next node in
* the list.
*/
if (this.tail) {
this.tail.next = newNode;
}
/*
* Assigns the new node as the
* tail of the list.
*/
this.tail = newNode;
},
remove: function() {
/*
* Creates a variable that
* references the current
* head of a list.
*/
var currentNode = this.head;
/*
* Assigns the head of the
* list to the node next to
* the current head.
*/
this.head = currentNode.next;
/*
* Sets the initial head of
* the list to null.
*/
currentNode = null;
},
contains: function(value) {
/*
* Creates a variable that
* references the current
* head of a list.
*/
var currentNode = this.head;
/*
* Continues iteration while
* there is a node in the
* list.
*/
while (currentNode) {
/*
* If the current node matches
* the target value, then
* return true.
*/
if (currentNode.data === value) {
return true;
}
...