javascript中数组是对象,所以在效率上,会差一点。所以有的时候可以选择链表。javascript原生是没有链表的,不过我们可以自己写一个对象,来模拟链表。
链表主要特点是:每个节点,都会指向它的后继。我们可以通过一个对象来定义
function node(e){
this.element=e;
this.next=null;
}//节点对象
node,element是指节点值,next表示下一节点.再定义一个链表对象linkList
function linkList(){
this.head=new node("head");
this.theNode=this.head;
}//链表对象
head用来表示链表的开始.theNode是中间变量,主要用于后面向链表插入值。在javascript中把一个对象复制给一个变量,是引用赋值,也就是所,对其中一个改变,会影响到所有,这一点很重要,这也方便了实现链表。下面是实现链表的一些操作,向链表添加元素,删除元素,元素查询.
linkList.prototype={
finds:function(e){//链表查找
var c=this.head;
while(c!=null&&c.element!=e){
c=c.next;
}
return c;
},
insert:function(ne,items){
var n=new node(ne);
if(arguments[1]==undefined){
this.theNode.next=n;
this.theNode=n;
}else{
var c=this.finds(items);
if(c==null){//没有查找到元素
console.log(ne+"插入位置不存在");
}else{
if(c.next==null){
this.theNode=n;
}
n.next=c.next;
c.next=n;
}
}
},//链表插入
remove:function(items){
var c=this.findLast(items);
if(c==null){
console.log("删除元素不存在");
}else{
c.next=c.next.next;
}
},//删除链表项
findLast:function(items){
var c=this.head;
while(c!=null&&c.next.element!=items){
c=c.next;
}
return c;
},
show:function(){
var c=this.head.next;
//console.log(c);
while(c!=null){
console.log(c.element);
c=c.next;
}
}//显示列表
}
下面是例子,
var l=new linkList();
l.insert("my");
l.insert("name");
l.insert("is","name");
l.insert("cjp");
l.show();
l.remove("cjp");
console.log("删除元素后:");
l.show();
l.insert("mc","name");
l.show();
在控制台,打印出结果是正确的
这就基本实现链表了。