The following is a list class
function LinkedList () {
Node represents the item to be added to the list
var node=function (Element) {
This.element=element;
This.next=null;
};
var length=0;//the number of stored list items
var Head=null;//head stores a reference to the first node
Append an element to the tail of a linked list
This.append=function (Element) {
var node=new node (element),
Current
if (head===null) {
Head=node;
}else{
Current=node;
while (Current.next) {
Current=current.next;
}
Current.next=node;
}
length++;
};
//Insert element anywhere in the list
This.insert=function (position,element) {
if (position>=0&&position<=length {
var node=new node (element),
Current=head,
Previous,
Index=0;
if (position===0) {
node.next=current;
Head=node;
}else{
while (index<position) {
previous=current;
Previous.next=node;
index++;
}
Node.next=current;
Previous.next=node;
}
length++;
return true;
}else{
return false;
}
};
Remove an element from a linked list
This.removeat=function (position) {
if (position>-1 && position<length) {
var current=head,
Previous
index=0;
if (position===0) {
Head=current.next;
}else{
while (index<position) {
Previous=current;
Current=current.next;
index++;
}
Previous.next=current.next;
}
length--;
return current.element;
}else{
return null;
}
};
Returns the position of the element in the linked list
This.indexof=function (Element) {
var current=head,
Index=-1;
while (current) {
if (element===current.element) {
return index;
}
index++;
Current=current.next;
}
return-1;
};
Remove an Element
This.remove=function (Element) {
var index=this.indexof (Element);
Return This.removeat (index);
};
Determine if the linked list is empty
This.isempty=function () {
return length===0;
};
Returns the length of the linked list
This.size=function () {
return length;
};
Converts a LinkedList object to a string
This.tostring=function () {
var current=head,
String= "";
while (current) {
String=current.element;
Current=current.next;
}
return string;
};
};
var list=new linkedlist ();
List.append (15);
List.append (10);
List.insert (1,11);
List.removeat (2)
Console.log (List.size ());
Create a linked list with a JS object