LinkedListDemo

by davidjb95

HTML

<input type="textbox" id="LinkName" Value="New Node" />
<input type="button" id="AddLink" value="Add Node to List" onClick="addNode();" />
<p id='output'></p>

JavaScript

function addNode() {
	var value = document.getElementById("LinkName").value;
  ll.add(value);
 document.getElementById('output').innerHTML = ll.toString();
}
var LinkedList = function () {
    
    var LinkedListNode = function (content) {
        this.next = null;
        this.content = content;
    };
    this.add = function (content) {
        if (this.head == null) {
            this.head = new LinkedListNode(content);
            return this.head;
        }
        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.toString = function () {
    var i = 1;
    var str = 'Linked List <br/>'
    var node = this.head;
    while (node != null) {
        str += i + ':  Node: ' + node.content;
        i++;
        str += '<br/>';
        node = node.next;
    }
    return str;
};

// Create a Linked List and Add Nodes
var ll = new LinkedList();
ll.add('A');
ll.add('B');
ll.add('C');
ll.add('D');
ll.add('E');
document.getElementById('output').innerHTML = ll.toString();