LinkedListDemo
by davidjb95
HTML
<input type="textbox" id="LinkName" Value="New Node" />
<input type="button" id="AddLink" value="Add Node to List" onClick="addNode();" />
<input type="button" id="AddLink" value="Bubble Sort" onClick="LinkedList.prototype.bubbleSort();" />
<p id='output'></p>
JavaScript
function addNode() {
var value = parseInt(document.getElementById("LinkName").value);
ll.add(value);
length++;
LinkedList.prototype.bubbleSort();
}
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.bubbleSort = function (){
var swapped;
do {
var node = ll.head;
swapped = false;
for(i = 1; i < length; i++){
if(node.content < node.next.content){
var temp = node.content;
node.content = node.next.content;
node.next.content = temp;
swapped = true;
}
node = node.next;
}
} while (swapped);
document.getElementById('output').innerHTML = ll.toString();
}
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();
var length = 0;
for(i = 0; i < 20; i++){
ll.add(Math.floor(Math.random() * 25 + 1))
length++;
}
document.getElementById('output').innerHTML = ll.toString();