LinkedListDemo

by davidjb95

HTML

<input type="textbox" id="LinkName" Value="New Node" />
<input type="button" id="AddLink" value="Add Node to List" onClick="addNode();" />
<input type="button" id="AddLink" value="Bubble Sort" onClick="LinkedList.prototype.bubbleSort();" />
<p id='output'></p>

JavaScript

function addNode() {
	var value = document.getElementById("LinkName").value;
  ll.add(value);
 document.getElementById('output').innerHTML = ll.toString();
}
var LinkedList = function () {
    var LinkedListNode = function (content) {
        this.next = null;
        this.content = content;
       	
    };
    this.add = function (content) {
        if (this.head == null) {
            this.head = new LinkedListNode(content);
            return this.head;
        }
        if (this.tail == null) {
            this.tail = new LinkedListNode(content);
            this.head.next = this.tail;
            return this.tail;
        };
        this.tail.next = new LinkedListNode(content);
        this.tail = this.tail.next;
        this.tail.next = null;
        return this.tail;
    }; 
}
LinkedList.prototype.bubbleSort = function (){
	var swapped = false;
  var node = ll.head;
  do {
  for(i = 0; i < 4; i++){
  if(node.content < node.next.content){
  		var temp = node.content;
      node.content = node.next.content;
      node.next.content = temp;
      swapped = true;
      alert(swapped);
      }
      node = node.next;
      
  }
  alert("after" + swapped);
  } while(swapped = true);
  alert("test");
  document.getElementById('output').innerHTML = ll.toString();
}
LinkedList.prototype.toString = function () {
    var i = 1;
    var str = 'Linked List <br/>'
    var node = this.head;
    while (node != null) {
        str += i + ':  Node: ' + node.content;
        i++;
        str += '<br/>';
        node = node.next;
    }
    return str;
};

// Create a Linked List and Add Nodes
var ll = new LinkedList();
ll.add(7);
ll.add(5);
ll.add(8);
ll.add(2);
ll.add(1);
document.getElementById('output').innerHTML = ll.toString();