Home >Web Front-end >JS Tutorial >Example of linked list data structure implemented in JavaScript_javascript skills

Example of linked list data structure implemented in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:06:261219browse

This example uses javascript to create a linked list. .
and sorted that. .

Can also be extended on GenericList general linked list.
Achieve various sorting and add, delete and modify node points. .

Copy code The code is as follows:

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

function GenericList(){
this.head=null;
this.current=null;
//Press 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.current.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("Unsorted linked list");
sl.print();
sl.BubbleSort();
alert("Sorted linked list from small to large");
sl.print();

})("1","2","3","4")


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn