Sorted Linked List
by Ron Eaglin
HTML
Add to List
<input type="textbox" id="content"/>
<input type="button" id = "go" onclick="addToList();" value = "Add"/>
<p id="list">
</p>
JavaScript
var SortedLinkedList = function() {
this.head = null;
}
var SortedLinkedListNode = function(_content) {
this.content = _content;
this.next = null;
}
SortedLinkedList.prototype.add = function(_content) {
var node = new SortedLinkedListNode(_content);
// no head - make head
if (this.head == null) {
this.head = node;
return this;
}
// make new head if less than head
if (node.content < this.head.content) {
node.next = this.head;
this.head = node;
return this;
}
this.head.add(this.head, node);
return this;
}
SortedLinkedListNode.prototype.add = function(p, n){
// put in front if less than
if (n.content < this.content) {
p.next = n;
n.next = this;
return this;
}
// put at tail if greater than and no next
if (this.next == null) {
p.next = this;
this.next = n;
return this;
}
// pass to next node if greater than and next exists
return this.next.add(this, n);
}
SortedLinkedList.prototype.toString = function() {
var str = "";
var node = this.head;
while (node != null) {
str += node.content + ":";
node = node.next;
}
return str;
}
var list = new SortedLinkedList();
function addToList() {
list.add(document.getElementById("content").value);
document.getElementById("content").value = "";
document.getElementById("list").innerHTML = list.toString();
}