Doubly linked LIst

by Prasad Gavande

HTML

<p id='output'></p>

JavaScript

var DoubleLinkedList = function() {

  this.head = 0;
  this.tail = 0;
  this.length = 5;

  var LinkedListNode = function(content) {
    this.next = 0;
    this.last = 0;
    this.content = content;
  };

  this.add = function(content) {
    if (this.head == 0) {
      this.head = new LinkedListNode(content);
      return this.head;
    }
    if (this.tail == 0) {
      this.tail = new LinkedListNode(content);
      this.head.next = this.tail;
      this.tail.last = this.head;
      return this.tail;
    };
    this.tail.next = new LinkedListNode(content);
    this.tail.next.last = this.tail;
    this.tail = this.tail.next;
    this.tail.next = 0;
    return this.tail;
  };
}

DoubleLinkedList.prototype.length = function() {
  var i = 0;
  var node = this.head;

  while (node != 0) {
    i++;
    node = node.next;
  }
  return i;
};

DoubleLinkedList.prototype.toString = function() {
  var i = 1;
  var str = 'Linked List with ' + this.length + ' nodes <br/>';
  var node = this.head;


  while (node != 0) {
    str += i + ': Node Value: ' + node.content;
    str += ' / Next Node Value: ' + node.next.content;
    str += " / Last Node Value: ";

    if (node.last == 0) str += ' null';
    else str += node.last.content;
    i++;
    str += "<br>";
    node = node.next;
  }
  return str;
};

var lln = new DoubleLinkedList();

lln.add(' Head Node');
lln.add(' Second Node');
lln.add(' Third Node');
lln.add(' Fourth Node')
lln.add(' Tail Node');

document.getElementById('output').innerHTML = lln.toString();