List Example

by Ron Eaglin

HTML

<br /><br /> Name of Node being added:
<input type="textbox" id="LinkName" Value="New Node" /><br/>
<input type="button" id="CreateList" value="Create New List" onClick="createList();" />
<input type="button" id="AddLink" value="Add Node to List" onClick="addNode();" />
<p id="output"></p>
<br />

JavaScript

var list = null;

function createList() {
  document.getElementById("output").innerHTML = "";
  list = new List("A");
  list.addNode("B");
  list.addNode("C");
  list.addNode("D");
  list.addNode("E");
  document.getElementById("output").innerHTML = list.print();
}


function addNode() {
  var value = document.getElementById("LinkName").value;
  list.addNode(value);
  document.getElementById("demo").innerHTML = list.print();
}


// Define the link object
function Node(_value, _last) {
  // This is a possible implementation of a Doubly Linked List
  this.value = _value; // The value stored
  this.last = _last; // A pointer to the previous link
  this.next = null; // a pointer to the next link
  return this; // returns the created node
}

Node.prototype.asString = function() {
  return "Node Value:" + this.value + "<br/>";
}


// Define the List object
function List(_value) { // We will define the list with the first link defined
  this.length = 0;
  this.addNode(_value); 
 }
//Function to add node to list
List.prototype.addNode = function(_value) {
  if (this.length == 0){
    this.length = 1;
    this.head = new Node(_value, null); // Pointer TO the head is null
    this.last = this.head; // When created - head and last are the same.
  }
  else{
    var node = new Node(_value, this.last);
    this.last.next = node;
    this.last = node;
  }
  

}

// This is a very simple print routine - it starts at the head
// and moves through the list
List.prototype.print = function() {
  var s = "";
  var n = this.head;

  while (n != null) {
    s += n.asString();
    n = n.next;
  }

  return s;
}