首頁  >  文章  >  web前端  >  用js物件建立鍊錶

用js物件建立鍊錶

高洛峰
高洛峰原創
2016-10-08 14:57:091659瀏覽

//以下是一個鍊錶類別

function LinkedList(){


//Node表示要加入列表的項目
var Node=function(element){

<br/>

  〜 null;
};

var length=0;//儲存清單項目的數量
var head=null;//head儲存的是第一個節點的引用

//向鍊錶尾部追加元素

this. append=function(element){
  var node=new Node(element),
    current;

  if(head===null){    〜 
    current=node;

    while( current.next){
      current=current.next;
    }

    〜.nextnodnodnolextnoded;
};


//在鍊錶的任意位置插入元素
this.insert=function (position,element){
  if(position>=0&&position
    var node=new Node(element),
      current=head,
      previous,

      index=0;


    if(position=== 0){
      node.next=current;
      head=node;

     head=node;

    }        previous=current;
        previous.next=node }
      node.next= current;
      previous.next=node;
    }

    length++;    return false;
  }
};

//從鍊錶中移除元素
this.removeAt=function( position){
  if(position>-1 && position    var current=head,
     『previous,
        if(position===0){
      head=current.next;
    } else{

      while(index        previous=current;
        current=current.next;
        index++;

      }

      previous.next=current.next;

    }

    length--;

    return current 。 index=-1;

  while(current){
    if(element===current.element){
      return index;
     『  current=current.next;
  }

  return -1;
};


//移除某個元素
this.remove=function(element){
  var index=this.indexOf(element);
  return this.removeAt(index);
};

//this鍊錶是否為空
/this鍊錶是否為空
//this鍊錶是否為空

/this鍊錶是否為空

/this鍊錶是否為空
//this鍊錶是否為空.isEmpty=function(){
  return length===0;
};

//返回鍊錶的長度
this.size=function(){
return length;List成一個字串

this.toString=function(){
  var current=head,
  string="";

  nhile(current){ .next;
  }
return string;

};


};

var list=new LinkedList();
list.append(15);

list.append(10);

list.insert(1,11);

list.append(10);

list.insert(1,11);
list.remove (2)
console.log(list.size());



陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn