Demonstration - Doubly Linked List

Dr Eaglan demonstrates the concept of list. It is designed to help students get started with how to implement their lists and aid the student in building their List and Node objects from scratch.

by Neil Daley

HTML

This is a demonstration of the concept of making a Linked List. There are 2 object involved here List and Node.
<br/>
<br/>
<input type="button" id="CreateList" value="Create List" onClick="createList();" />
<br/>
<br/> Name of Node being added:
<input type="textbox" id="LinkName" Value="New Node" />
<input type="button" id="AddLink" value="Add Node to List" onClick="addNode();" />
<p id="demo"></p>
<br/> You should be able to build both Doubly and Singly Linked Lists - read more at <a href='https://en.wikipedia.org/wiki/Linked_list'>Wikipedia Linked Lists</a>

JavaScript

var list = null;

function createList() {
  var value = document.getElementById("LinkName").value;
  list = new List(value);
  document.getElementById("demo").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 = 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.
}

List.prototype.addNode = function(_value) {
  // A function to add a link to the list - you will have to write this
  alert("This function must be written");

}

// 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;
}