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 double linked list not sorted
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;
}
//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;
}
aList.sort();
return s;
}
var aList = new LinkedList();
function addNode() {
var c = document.getElementById("v").value;
aList.add(c);
document.getElementById("output").innerHTML=aList.print();
document.getElementById("v").value = randomString(3);
}
function randomString(_length) {
var chars = "abcdefghijklmnopqrstuvwxyz0123456789"
var randomstring = '';
for (var i = 0; i < _length; i++) {
var ranNum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(ranNum, ranNum + 1);
}
return randomstring;
}