您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

用js对象创建链表

2024/6/26 11:01:19发布34次查看
//以下是一个链表类
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
var node=new node(element),
current=head,
previous,
index=0;
if(position===0){
node.next=current;
head=node;
}else{
while(indexprevious=current;
previous.next=node;
index++;
}
node.next=current;
previous.next=node;
}
length++;
return true;
}else{
return false;
}
};
//从链表中移除元素
this.removeat=function(position){
if(position>-1 && positionvar current=head,
previous,
index=0;
if(position===0){
head=current.next;
}else{
while(indexprevious=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());
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product