Create a linked list using js objects
// The following is a linked list
Function compute list (){
// Node indicates the item to be added to the list
Var Node = function (element ){
This. element = element;
This. next = null;
};
Var length = 0; // number of items in the storage list
Var head = null; // The head stores the reference of the first node.
// Append an element to the end of the 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 an element anywhere in the linked 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 Previous = current;
Previous. next = node;
Index ++;
}
Node. next = current;
Previous. next = node;
}
Length ++;
Return true;
} Else {
Return false;
}
};
// Remove elements from the linked list
This. removeAt = function (position ){
If (position>-1 & position Var current = head,
Previous,
Index = 0;
If (position = 0 ){
Head = current. next;
} Else {
While (index Previous = current;
Current = current. next;
Index ++;
}
Previous. next = current. next;
}
Length --;
Return current. element;
} Else {
Return null;
}
};
// Return 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 );
};
// Judge whether the linked list is empty
This. isEmpty = function (){
Return length = 0;
};
// Returns the length of the linked list.
This. size = function (){
Return length;
};
// Convert the listing list object into a string
This. toString = function (){
Var current = head,
String = "";
While (current ){
String = current. element;
Current = current. next;
}
Return string;
};
};
Var list = new vertex list ();
List. append (15 );
List. append (10 );
List. insert (1, 11 );
List. removeAt (2)
Console. log (list. size ());