前言與鏈表實現數組

緣起

最近工做上須要依照現有數據生成嵌套json對象形式的組織機構列表,一時以爲無從下手,請教同事大神才知道此乃數據結構相關知識,遂惡補相關基礎並在此記錄。 javascript

數據結構能夠分爲:一、列表;二、線性;三、樹形;四、圖 四種基本結構。何爲數據結構?我理解就是數據的結構。。。即承載數據的形式。數據結構中的線性結構有數組和鏈表,本文即對鏈表進行簡單總結,在後續文章中會實現幾種基本的數據結構。java

鏈表

1 鏈表是什麼

鏈表相關概念json

2 用鏈表實現數組和其基本操做,如下附上代碼
function ARRAY(){
  var INDEX=-1;
  var HEAD=null;
  var OBJ=null;
  //添加元素
  this.add=function(e){
    function Element(value){
      this.value=value;
    }
    e=new Element(e);
    if(INDEX==-1){
      OBJ=e;
      HEAD=e;
      INDEX++;
    }else{
      INDEX++;
      OBJ.next=e;
      OBJ=OBJ.next;
    }
    return HEAD;
  }
  //刪除最後一個元素
  this.deleteLast=function(){
    for(var i=HEAD;i!=undefined;i=i.next){
      if(i.next.next==undefined){
        i.next=null;
      }
    }
    return HEAD;
  }
  //按序號取元素
  this.get=function(Inx){
    var index=0;
    for(var i=HEAD;i!=undefined;i=i.next){
      index++;
      if(index==Inx){
        return i;
      }
    }
  }
  //按位置插入元素
  this.insert=function(Inx,e){
    function Element(value){
      this.value=value;
    }
    e=new Element(e);
    if(Inx==0){
      e.next=HEAD;
      HEAD=e;
    }else{
      var currentItem=this.get(Inx);
      var sufItem=this.get(Inx+1);
      e.next=sufItem;
      currentItem.next=e;
    }
    return HEAD;
  }
  //刪除特定位置元素
  this.deleteElement=function(Inx){
    if(Inx==0){
      var sufItem=this.get(Inx+1);
      HEAD=sufItem;
    }else{
      var preItem=this.get(Inx-1);
      var sufItem=this.get(Inx+1);
      preItem.next=sufItem;
      }
    return HEAD;
  }
}

同時提供兩種遍歷鏈表的方法數組

//遍歷鏈表(遞歸)
function loop(head){
  if(head.next==undefined){
    return;
  }
  return loop(head.next);
}
//遍歷鏈表(非遞歸)
function loopLinkedList(head){
  for(var i=head;i!=undefined;i=i.next){
    console.log(i);
  }
}

具體使用方法數據結構

var obj = new ARRAY();
console.time('addtest');
obj.add('aaa');
obj.add('bbb');
obj.add('ccc');
obj.add('ddd');
var head=obj.add('eee');
console.log(head);
console.timeEnd('addtest');
相關文章
相關標籤/搜索