Basic Implementation of Linked List - No Array
by Taylor Zimmerman
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;
};
this.tail.next = new LinkedListNode(content);
this.tail = this.tail.next;
this.tail.next = null;
return this.tail;
};
}
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();