Assignment 4

Linked List

by F Fornos

HTML

<h3>
Insert into List:
</h3>
<input type="textbox" id="addObject" Value="Add text here..." />
<input type="button" id="myList" value="Insert" onClick="addtoList();" />
<p id="demo"></p>



<p id='output'></p>

JavaScript

var list = function() {

  this.head = 0;
  this.tail = 0;

  var listNode = function(value, idtail) {

    this.next = 0;
    this.id = idtail + 1;
    this.value = value;

  };

  this.add = function(value) {
    //create list head
    if (this.head == 0) {
      this.head = new listNode(value, 0);
      return this.head;
    }

    //create list tail
    if (this.tail == 0) {
      this.tail = new listNode(value, 1);
      this.head.next = this.tail;
      return this.tail;
    };

    this.tail.next = new listNode(value, this.tail.id);
    this.tail = this.tail.next;
    this.tail.next = 0;
    return this.tail;
  };
}

list.prototype.length = function() {
  var i = 0;
  var node = this.head;

  while (node != 0) {
    i++;
    node = node.next;
  }
  return i;
};

list.prototype.toString = function() {
  var i = 1;
  var str = "Total Entries: " + this.length() + "<br/>";
  var node = this.head;


  while (node != 0) {
    str += "---------------------------------------<br/>"+ "Entry No. " + node.id + "<br/>" + "Contents: " + node.value + "<br/>";
    str += "[Next list entry: ";

    if (node.next == 0) str += " empty]";

    if (node.next != 0) str += node.next.value + "]";

    i++;
    str += "<br/>";
    node = node.next;
  }
  return str;
};

//create a list with its nodes
var ll = new list();
//add content nodes to the list 
function addtoList() {
  var newaddObject = document.getElementById("addObject").value;

  ll.add(newaddObject);

  document.getElementById("output").innerHTML = ll.toString();

}