js建立鏈表

來源:互聯網
上載者:User

標籤:

function LinkedList(){


//Node表示要加入列表的項
var Node=function(element){
  this.element=element;
  this.next=null;
};

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

//向鏈表尾部追加元素
this.append=function(element){
  var node=new Node(element),
    current;

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

   }else{
    current=node;

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

    current.next=node;

  }

  length++;
};

//在鏈表的任意位置插入元素
this.insert=function(position,element){
  if(position>=0&&position<=length){

    var node=new Node(element),
      current=head,
      previous,
      index=0;

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

    }else{
      while(index<position){
        previous=current;
        previous.next=node;
        index++;
      }
      node.next=current;
      previous.next=node;
    }

    length++;

    return true;
  }else{
    return false;
  }
};

//從鏈表中移除元素
this.removeAt=function(position){
  if(position>-1 && position<length){
    var current=head,
      previous,
      index=0;

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

      while(index<position){
        previous=current;
        current=current.next;
        index++;
      }
      previous.next=current.next;

    }

    length--;

    return current.element;
  }else{
    return null;
  }
};

//返回元素在鏈表中的位置
this.indexOf=function(element){
  var current=head,
    index=-1;

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

  return -1;
};

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

//判斷鏈表是否為空白

this.isEmpty=function(){
  return length===0;
};

//返回鏈表的長度
this.size=function(){
return length;
};

//把LinkedList對象轉換成一個字串

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

  while(current){
    string=current.element;
    current=current.next;
  }
  return string;
};

};

var list=new LinkedList();
list.append(15);
list.append(10);
list.insert(1,11);
list.removeAt(2)
console.log(list.size());

js建立鏈表

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.