Reputation: 103
I am trying to write some JavaScript in JsFiddle where a doubly linked list is created, then a node can be added to the end. I have done so, but want to fill the list differently.
Here is what I have so far
HTML
Create A New List, Then Add A Node!
<br/>
<br/>
<input type="textbox" id="Values" />
<input type="button" value="Create New List" onClick="createList()" />
<input type="button" value="Add a Node" onClick="addNode()" />
<div id="output">
</div>
JavaScript
var newList = new DoublyLinked();
function DoublyLinked() {
this.head = null;
this.tail = null;
this.length = 0;
}
function NewNode() {
this.values = null;
this.next = null;
this.prev = null;
return this;
}
DoublyLinked.prototype.add = function(values) {
var node = new NewNode();
node.values = values;
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;
}
function addNode() {
var values = document.getElementById("values").value;
newList.add(values);
newList.print();
}
DoublyLinked.prototype.print = function() {
if (this.head === null) return "Empty List";
var display = " ";
var counter = 0;
var node = this.head;
while (node !== null) {
counter = counter + 1;
display += "Node: " + counter + " Content: " + node.values + "</br>";
node = node.next;
}
document.getElementById("output").innerHTML = display;
}
function createList(values) {
for (var i = 0; i < 5; i++) {
values = String.fromCharCode(65 + i);
newList.add(values);
newList.print();
}
}
The code above should insert nicely into fiddle if testing, however JS needs to have set no wrap in body load type
Instead of populating the list at the end with a loop in function createList, I would like to populate it with something like shown below, having trouble writing the code to populate the list differently
function createList(values) {
newList.add("A")
newList.add("B")
newList.add("C")
newList.add("D")
newList.add("E")
newList.print();
With this how it is ( the piece of code above in place of the loop) I can generate the list but not add a node
Upvotes: 3
Views: 494
Reputation: 103
The problem is the id Values in HTML, the id being called is values, no capitals. Values was not being instantiated, fixed the typo. Runs great.
Upvotes: 1