首页 > 语言 > JavaScript > 正文

JavaScript实现的链表数据结构实例

2024-05-06 14:43:50
字体:
来源:转载
供稿:网友

此例是javascript来建立链表。。
并对此进行了排序。。

还可以在GenericList一般链表上进行扩展。
实现各种排序及增,删,改结点。。

代码如下:
function Node(){
  this.data=null;
  this.next=null;
}

function GenericList(){
  this.head=null;
  this.current=null;
  //打出所有的链表结点
  this.print= function(){
  this.current=this.head;
   while(this.current!=null){
      alert(this.current.data);
      this.current=this.current.next;
    }
 
  },
  //建立链表
  this.addHead =function(t){
     
 
      var node=new Node();
      node.data=t;
      node.next=this.head;
      this.head=node;
 
  }
 
 

}


function SortList(){
//冒泡排序链表
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;

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选