Doubly Linked List Created Randomly
A simple demonstration of a Doubly Linked List with an interface to add nodes to the list. This can be used to Fork to applications that require a Linked List. Includes push and pop functions.
by Ron Eaglin
HTML
<input type="button" value="Create Random List" onclick="createList(10)" />
<input type="textbox" id="v" value="Node 1" />
<input type="button" value="Add Node" onclick="addNode()" />
<br/><br/>
<div id="output">
</div>
<br/>
<input type="button" value="Pop Node" onclick="popNode()" />
<br/><br/>
<div id="output2">
</div>
JavaScript
function LinkedList() {
this.head = null;
this.tail = null;
this.length = 0;
}
function Node() {
this.next = null;
this.prev = null;
this.content = null;
}
LinkedList.prototype.add = function(_content) {
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.push = function(_content) {
this.add(_content);
}
// Pop will pop of the entire node
LinkedList.prototype.pop = function() {
if (this.head == this.tail) {
var temp = this.head;
this.head = null;
this.tail = null;
return temp;
}
var oldtail = this.tail;
var newtail = this.tail.prev;
newtail.next = null;
this.tail = newtail;
return oldtail;
}
LinkedList.prototype.print = function() {
if (this.head == null) return "Empty List";
var s = "";
var node = this.head;
while (node != null) {
s += node.content + " ";
node = node.next;
}
return s;
}
var i = 1;
var aList = new LinkedList();
function addNode() {
var c = document.getElementById("v").value;
aList.add(c);
document.getElementById("output").innerHTML = aList.print();
i++;
document.getElementById("v").value = "Node " + i;
}
function popNode() {
var oldtail = aList.pop();
if (oldtail == null) {
document.getElementById("output2").innerHTML = "List is Empty";
return;
}
document.getElementById("output2").innerHTML = "Popped Node: " + oldtail.content + "<br/>";
document.getElementById("output2").innerHTML += aList.print();
}
function createList(n) {
for (var i = 1; i <= n; i++) {
aList.push(createRandomString());
}
document.getElementById("output").innerHTML =...