Real Double Linked list
by Nyle Anderson
HTML
<input type = "textbox" id="v" value="aaa" />
<input type="button" value="Add Node" onclick="addNode()" />
<div id="output">
</div>
JavaScript
//working sorted double linked list
function LinkedList() { //defines the list
this.head = null;
this.tail = null;
this.length = 0;
}
function Node() { //defines the node
this.next = null;
this.prev = null;
this.content = null;
}
LinkedList.prototype.add = function(_content) {
//defines adding node
var node = new Node(); node.content = _content
if(this.head == null){
this.head = node; this.length = 1;
return node;
}
if (this.tail == null) {
this.tail = node;
this.tail.prev = this.head;
this.head.next = this.tail;
this.length = 2;
return node;
}
this.tail.next = node;
node.prev = this.tail;
this.tail = node;
this.length++;
return node;
}
LinkedList.prototype.addSorted = function(_content) {
if(this.head == null) {return this.add(_content); }
var node = new Node(); node.content = _content;
if(_content < this.head.content) {
this.head.prev = node;
node.next = this.head;
this.head = node;
return node;
}
var cnode = this.head;
while (cnode.next != null) {
if ((_content > cnode.content) && (_content < cnode.next.content)){
node.prev = cnode;
cnode.prev = node;
node.next = cnode.next;
cnode.next.prev = node;
cnode.next = node;
}
//while node.content > cnode.content || node.content > cnode.content.next
//node
cnode = cnode.next;
return node;
}
return this.add(_content);
}
//to make a stack add pop and push functions
//to make a queue add enqueue and dequeue functions
LinkedList.prototype.print = function () {
if (this.head == null) return "Empty List";
var s = "";
var node = this.head;
while (node != null){
s += node.content + "<br/> ";
node = node.next;
}
return s;
}
var aList = new LinkedList();
function addNode() {
var c = document.getElementById("v").value;
aList.addSorted(c);
document.getElementById("output").innerHTML=aList.print();
document.getElementById("v").value =...