List Assignment 4
by pat spag
HTML
Step 1: Create Linked List <br/>
<input type ="button" id="CreateList" value="Create List" onClick="createList()" />
<br/>
<br/>
Step 2: Add Node
<input type="text" id="nodeValue" value="" />
<br/>
<input type="button" value="Add to List" onClick="addNode()" />
<br/>
<br/>
<br/>
<div id="output">
</div>
JavaScript
var list;
function createList() {
list = new linkedList();
//populating list with 5 nodes; A,B,C,D,E
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
document.getElementById("output").innerHTML = list.print();
}
//following example video
function linkedList(head, tail, length) { //list Properties
this.head = null;
this.tail = null;
this.length = 0;
}
function node(id, content, next, last) {//required node properties
this.id = null;
this.content = content;
this.next = next;
this.last = last;
};
linkedList.prototype.add = function(content) {
// create prototype add function
id=null;
if (this.head == null) {
this.head = new node(id, content, null, null);
this.length = 1;
return;
}
var previousNode = this.head; //creating a tail
for (var i = 0; i < this.length - 1; i+=1) {
previousNode = previousNode.next;
}
//shifting tail
var nextNode = new node(null, content, null, previousNode);
previousNode.next = nextNode;
this.length += 1;
}
linkedList.prototype.print = function(){
var display = "";
var currentNode = this.head;
while (currentNode != null) {
display += currentNode.content + " ";
currentNode = currentNode.next;
}
return display;
}
function addNode(){//add user-entered node to list
var nodeValue = document.getElementById("nodeValue").value;
list.add(nodeValue);
document.getElementById("output").innerHTML = list.print();
}