An instance of a linked list data structure implemented by JavaScript

  • 2020-05-24 05:13:19
  • OfStack

This example is javascript to build a linked list.
And sorted it out.

You can also extend on linked lists like GenericList1.
Achieve a variety of sorting and add, delete, change nodes.


function Node(){
  this.data=null;
  this.next=null;
} function GenericList(){
  this.head=null;
  this.current=null;
  // Type all the list nodes
  this.print= function(){
  this.current=this.head;
   while(this.current!=null){
      alert(this.current.data);
      this.current=this.current.next;
    }
 
  },
  // Build list
  this.addHead =function(t){
     
 
      var node=new Node();
      node.data=t;
      node.next=this.head;
      this.head=node;
 
  }
 
  }
function SortList(){
// Bubble sort linked lists
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<arguments.length;i++)
 {sl.addHead(arguments[i]);
 }
 alert(" Unsorted linked list ");
 sl.print();
 sl.BubbleSort();
  alert(" Sorted linked list   Since the childhood ");
 sl.print(); })("1","2","3","4")


Related articles: