Examples of linked list data structures implemented by JavaScript
In this example, javascript is used to create a linked list ..
And sorted ..
It can also be expanded on the GenericList General linked list.
Sort, add, delete, and modify nodes ..
The Code is as follows:
Function Node (){
This. data = null;
This. next = null;
}
Function GenericList (){
This. head = null;
This. current = null;
// Print all linked list nodes
This. print = function (){
This. current = this. head;
While (this. current! = Null ){
Alert (this. current. data );
This. current = this. current. next;
}
},
// Create a linked list
This. addHead = function (t ){
Var node = new Node ();
Node. data = t;
Node. next = this. head;
This. head = node;
}
}
Function SortList (){
// Bubble sort linked list
This. BubbleSort = function ()
{
If (this. head = null | this. head. next = null)
{
Return;
}
Var swapped;
Do {
This. previous = null;
This. current = this. head;
Var swapped = false;
While (this. current. next! = Null)
{
If (this. Present. data-this.current.next.data> 0)
{
Var tmp = this. current. next;
This. current. next = this. current. next. next;
Tmp. next = this. current;
If (this. previous = null)
{
This. head = tmp;
}
Else
{
This. previous. next = tmp;
}
This. previous = tmp;
Swapped = true;
}
Else
{
This. previous = this. current;
This. current = this. current. next;
}
}
} While (swapped );
}
}
SortList. prototype = new GenericList ();
(Function Main (){
Var sl = new SortList ();
For (var I = 0; I
{Sl. addHead (arguments [I]);
}
Alert ("unordered Linked List ");
Sl. print ();
Sl. BubbleSort ();
Alert ("sorted linked lists from small to large ");
Sl. print ();
}) ("1", "2", "3", "4 ")