LinkedList

by aren_anderson

HTML

<input type="button" id="btnCreate" value="Create List" onclick="createList()"/>
<br/>
<input type="textbox" id="tbNode" value="New Node"/>
<input type="button" id="btnNode" value="Add to List" onclick="addNode();"/>

<div id="output">
</div>

JavaScript

//Linked List object
function LinkedList(){
	this.head = null;
  this.tail = null;
  this.length = 0;
}

//Node object
function Node(){
	this.next = null;
  this.prev = null;
  this.content = null;
}

//function to add content to Node
LinkedList.prototype.add = function(_content){
	var node = new Node(); 
  node.content = _content;
  
  if (this.head == null){
  	this.head = node; 
    this.length = 1;
    return node;
  }


  if (this.tail == null){
  	this.tail = node;
    this.tail.prev = this.head;
    this.head.next = this.tail;
    this.length++;
    return node;
  }
  
  this.tail.next = node;
  node.prev = this.tail;
  this.tail = node;
  this.length++;
  return node;
}

//print the list in a way that is readable
LinkedList.prototype.print = function(){
	if (this.head == null) return "Empty List";
  var string = "";
  var node = this.head;
  while (node != null) {
  	string += node.content + "     ";
    node = node.next;
  }
  return string;
}

//instantiate a new list
var aList = new LinkedList();

//function to create a list containing 5 nodes
function createList(){
	aList.add("A");
  aList.add("B");
  aList.add("C");
  aList.add("D");
  aList.add("E");
	document.getElementById("output").innerHTML = aList.print();
}

//function to add a new node to the end of the list
function addNode(){
	var c = document.getElementById("tbNode").value;
  aList.add(c);
  document.getElementById("output").innerHTML = aList.print();
}