Add Sorted to List

Demonstrates how to add a node into a Singly Linked List directly into sorted location.

by vzufelt

HTML

<input type="textbox" id="v" value="1a2b3c" />
<input type="button" value="Add Node" onclick="addNode()" />

<div id="output">

</div>

JavaScript

function LinkedList() {
  this.head = null;
  this.tail = null;
  this.length = 0;
}
function Node() {
  this.next = null;
  this.prev = null;
  this.content = null;
}
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 = 2;
    return node;
  }
  this.tail.next = node;
  node.prev = this.tail;
  this.tail = node;
  this.length++;
  return node;
}
LinkedList.prototype.addSorted = function(_content) {
  if (this.head == null) {
    return this.add(_content);
  }
  var node = new Node();
  node.content = _content;

  if (_content < this.head.content) {
    this.head.prev = node;
    node.next = this.head;
    this.head = node;
    return node;
  }
  var cnode = this.head;
  while (cnode.next != null) {
    if ((_content > cnode.content) && (_content < cnode.next.content)) {
      node.prev = cnode;
      node.next = cnode.next;
      cnode.next.prev = node;
      cnode.next = node;
    }
    cnode = cnode.next;
    return node;
  }
  return this.add(_content);
}
LinkedList.prototype.print = function() {
  if (this.head == null) return "Empty List";
  var s = "";
  var node = this.head;
  while (node != null) {
    s += node.content + " <br/>  ";
    node = node.next;
  }
  return s;
}
var aList = new LinkedList();
function addNode() {
  var c = document.getElementById("v").value;
  aList.addSorted(c);
  document.getElementById("output").innerHTML = aList.print();
  document.getElementById("v").value = randomString(3);
}
function randomString(_length) {
  var chars = "abcdefghiklmnopqrstuvwxyz0123456789";
  var randomstring = '';
  for (var i = 0; i < _length; i++) {
    var ranNum = Math.floor(Math.random() * chars.length);
    randomstring += chars.substring(ranNum, ranNum + 1);
  }
  return...