首页 / JAVASCRIPT / 用js对象创建链表
用js对象创建链表
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了用js对象创建链表,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2374字,纯文字阅读大概需要4分钟。
内容图文
![用js对象创建链表](/upload/InfoBanner/zyjiaocheng/306/9ab6f1cdb8ad4098b466d24bed389744.jpg)
//以下是一个链表类
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对象创建链表所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。