js链表linkedList类(链表)

1,链表

***创键链表:

function linkedlist(){           //创建数据结构,一个对象,以后用来创建数据实例
  var   Node=function(element){  //辅助类,表示要添加进列表的项

this.element=element;   // 要添加的数据

this.next=null;   //指向列表下一项的指针;

}

var length=0;   //存储列表的项的长度;

var  head=null;   //存储第一个节点的引用;

}

***从链表增加元素:

this.append=function(element){
var node=new Node(element){  //  创建node项,把值传入

current;  // 创键一个迭代指针,可以遍历链表的;

if(head===null)  //如果链表是空的

  head=node;       //则node是链表的第一个项,使第一个项指向node

else{    //如果链表本来就有值

while(current.next){     //一直往下迭代寻找最后一个项

current=current.next;

}

current.next=node; //找到了最后一个项目,本来它的next=null,现在使它的next=node;

}

length++; //更新链表长度;

}

***从链表移除制定位置(position=5)元素:

this.removeAt=function(position){}

a, 这个元素是链表的第一个元素:current指向链表中的元素,令current=head;  head=current.next;直接抛弃current;

b.这个元素是链表的最后一个或中间的元素:

var index=0;//创建一个累加;

while(index<pisition)  //position是要删除的位置,比如5;

{

previous=current;  //创建指向迭代指针的前一个位置

current=current.next; //迭代指针向下寻找

index++;  

}    //index++执行后,index=3,{}中内容不再执行,current指向要删除元素的位置,previous指向前一个位置,令previous的下一个元素是current的下一个元素,即删除了current。

previous.next=current.next;

***tostring()获取链表中值的字符串:

this.tostring=function(){
var current=head;  //让current指向链表头部

var string='  ';

while(current){

string+=current.element   //current指向链表,可以引用元素。之前有个,var Node=function(element){  this.element=element}, 这个this指向LinkedList()链表。因为current=head,所以current可以直接引用数据。

current=current.next;    

}

return string;

***从链表查询元素位置Indexof():
this.indexOf=function(element){

var current=head;

var index=-1;

while(current){
index++;

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

current=current.next;

}}

return -1;

}

***从链表删除指定元素(element=hello):

this.remove=function(element){

var position=this.indexof(element);

 return     this.removeAt(position);

}

***询问链表是否为空:

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

***询问链表长度:

this.size=function(){
return  this.length; 

}

***返回head头指针:

this.getHead = function(){     return head; };


 

猜你喜欢

转载自blog.csdn.net/kalinux/article/details/81949180