List Example
by Ebony McCoy
HTML
<p id= "output"></p>
JavaScript
var LinkedList = function() {
this.head = null;
this.tail = null;
var LinkedListNode = function (content) {
this.next = null;
this.content = content;
}
this.add = function(content) {
//no head- create one
if(this.head == null) {
this.head = new LinkedListNode(content);
return this.head;
}
//no tail- create one
if(this.tail == null){
this.tail = new LinkedListNode(content);
this.head.next = this.tail;
return this.tail;
}
// if head and tail aren't null youre going to have to add a new tail and make old tail be in the middle
this.tail.next = new LinkedListNode(content);
this.tail = this.tail.next;
this.tail.next = null;
return this.tail;
}
}
//prototype function - create new methods and functions for the object
LinkedList.prototype.length = function(){
var i = 0;
var node = this.head;
while (node != null){
i++;
node = node.next;
}
return i;
}
LinkedList.prototype.toString = function(){
var i =1;
var str = "Linked List with " + this.length() + " nodes <br/>";
var node = this.head;
while( node != null){
str += i + ": Node Value: " + node.content;
str += " Next Node Value: ";
if(node.next == null) str += "null";
if(node.next != null) str += node.next.content;
i++;
str += "<br/>";
node = node.next;
}
return str;
}
//create a Linked List and Add nodes
var ll = new LinkedList();
ll.add("Content for head");
ll.add("Second Node");
ll.add("Last Node");
document.getElementById("output").innerHTML = ll.toString();