Lists

COP3530 Assignment 4

by Jake Jernigan

HTML

Name of Node being added:
<br/>
<input type="textbox" id="LinkName" Value="" />
<input type="button" id="CreateList" value="Show/Reset List" onClick="showList();" />
<br/>
<input type="button" id="AddLink" value="Add Node to List" onClick="addNode();" />
<p id="demo"></p>

JavaScript

var list = null;

function showList() {
  list = new List();
  list.addNode('Second');
  list.addNode('Third');
  list.addNode('Fourth');
  list.addNode('Fifth');
  document.getElementById("demo").innerHTML = list.print();
}

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

function Node(_value, _last) {
  this.value = _value;
  this.last = _last;
  this.next = null;
  return this;
}

function List() {
  this.length = 1;
  this.head = new Node('First', null);
  this.last = this.head;
}

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

List.prototype.addNode = function(value) {
  if (this.head == null) {
    this.head = new Node(value);
    return this.head;
  }
  if (this.tail == null) {
    this.tail = new Node(value);
    this.head.next = this.tail;
    return this.tail;
  };
  this.tail.next = new Node(value);
  this.tail = this.tail.next;
  this.tail.next = null;
  return this.tail;
}

List.prototype.print = function() {
  var s = "";
  var n = this.head;

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