I wrote this simple linked list in JavaScript. Feedback is welcome.
function Node(data)
{
this.next = null;
this.data = data;
}
function LinkedList()
{
this.length = 0;
this.head = null;
// add node with given value to the list.
this.add = function (value)
{
var node = new Node(value);
var temp;
if(this.length == 0)
{
this.head = node;
this.length++;
return;
}
temp = this.head;
// Move to the position where we can perform addition
// This logic is slightly different when we for example need to do search.
while(temp.next)
{
temp = temp.next;
}
temp.next = node;
this.length++;
return;
}
// Search for node with given value.
this.search = function (value)
{
// index where the node was found
var index = 0;
// If the list is empty there is no point in searching.
if(!this.head)
{
console.log("List is empty");
return;
}
var temp = this.head;
while(temp)
{
if(temp.data == value)
{
console.log("Found at: " + index);
return;
}
// move to next node
temp = temp.next
index++;
}
console.log("Node not found");
}
// Dump whole list
this.print = function()
{
if(!this.head)
{
console.log("List is empty");
return;
}
var temp = this.head;
while(temp)
{
console.log(temp.data);
temp = temp.next
}
}
// Remove node at index. Index starts from 0.
this.removeAtIndex = function (index)
{
var i = 0;
if(index < 0 || index >= this.length)
throw "Wrong index";
var temp = this.head;
if(!this.head)
return;
if(index == 0)
{
this.head = this.head.next;
this.length--;
return;
}
// Move to the position where we can perform delete.
for(i = 0; i < index - 1; i++)
{
temp = temp.next;
}
temp.next = temp.next.next;
this.length--;
return;
}
}
var x = new LinkedList();
x.add(200);
x.add(100);
x.add(300);
x.add(400);
x.print();
x.search(400);
x.removeAtIndex(2);
x.print();
x.search(400);