星空网 > 软件开发 > Java

用js对象创建链表

//以下是一个链表类

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对象创建链表

关键词:JS

JS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

如何避免国际物流中运输的风险?:https://www.ikjzd.com/articles/141226
神准!21年春夏女装上衣六大流行趋势,这些款都卖爆了! !:https://www.ikjzd.com/articles/141227
全球速卖通邮费那么贵怎么盈利 ​:https://www.ikjzd.com/articles/141228
亚马逊新手卖家需要避免的七大坑!:https://www.ikjzd.com/articles/141229
Google搜索引擎规则、用户搜索习惯及我们运营策略的调整:https://www.ikjzd.com/articles/141230
跨境搬砖有技巧-从波士顿矩阵看选品!:https://www.ikjzd.com/articles/141231
请问西安及周边5日游怎么安排?:https://www.vstour.cn/a/364173.html
图策全国免景点门票 预订景区门票优惠:https://www.vstour.cn/a/364174.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流