Linked Lists

by verashn

JavaScript

function Node (value) {
	this.data = value;
  this.next = null;
}

function LinkedList() {
  this.length = 0;
  this.head = null;
  this.tail = null;
}

LinkedList.prototype.print = function() {
  var current = this.head,
 			out = [];

  while (current !== null) {
    out.push(current.data);
    current = current.next;
  }

  return out.join(", ");
}

LinkedList.prototype.get = function(index) {
  if (index < 0 || index > this.length) {
    return null;
  }

  var result = this.head;
  for (var i = 0; i < index; i++) {
    result = result.next;
  }

  return result.data;
}

LinkedList.prototype.add = function(value) {
  var node = new Node(value);
  
  if (this.head === null) {
    this.head = node;
  } else {
    // add this node as next to current last node
    if (this.tail !== null) {
      this.tail.next = node;
    }
  }

  // set last node to the new node
  this.tail = node;

  this.length++;
};

var list = new LinkedList();
list.add('red');
list.add('orange');
list.add('yellow');
list.add('green');
list.add('blue');
list.add('navy');
list.add('violet');
console.log(list);
console.log(list.print());