链表存储有序的元素集合,但不同于数组,链表中的元素在内存中并不是连续放置的。每个元素由一个存储元素本身的节点和一个指向下一个元素的引用(也称指针或链接)组成。
相对于传统的数组,链表的好处在于,添加或移除元素的时候不需要移动其他元素,然而链表需要使用指针,因此实现链表时需要额外注意。数组的另一个细节是可以直接访问任何位置的任何元素,而要想访问链表中间的一个元素,需要从起点(表头)开始迭代列表直到找到所需的元素。
function Link(){
var length=0;//链表长度
var head=null;//头结点的引用
function Node(e){
this.element=e;//元素的值
this.next=null;//下一个元素的指针
}
this.insert1=function(e){//在链表尾部添加节点
var node=new Node(e);//实例化一个节点
var current;//用于遍历链表的指针
if(head==null){//列表中第一个节点
head=node;
}else{//循环列表,直到找到最后一项
current=head;
while(current.next){
current=current.next;
}
//找到最后一项,将其next赋值为node,建立链接
current.next=node;
}
//更新链表长度
length++;
}
this.insert2=function(e){//在链表尾部添加节点
this.insertAt(length,e);
}
this.insertAt=function(position,e){//在任意位置添加节点
if(position>=0&&position<=length){//检查是否越界
var node=new Node(e);//实例化一个节点
var current=head;
var previous;
var index=0;
if(position==0){
head=node;
node.next=current;
}else{
while(index<position){//找到元素位置
previous=current;
current=current.next;
index++;
}
previous.next=node;
node.next=current;
}
length++;
return true;
}else{
return null;
}
}
this.remove1=function(){//删除链表尾部节点
this.removeAt(length-1);
}
this.remove2=function(v){//删除某个值的节点
var index;
index=this.indexOf(v);//获取元素的位置
if(index!=null){
this.removeAt(index);//删除某个位置的节点
}else{
return null;
}
}
this.removeAt=function(position){//删除任意位置的节点
if(position>-1&&position<length){//越界判断
var current=head;
var previous;
var 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(e){//查找某个元素的位置
var current=head;
var index=0;
while(current){
if(current.element==e){
return index;
}
current=current.next;
index++;
if(index>=length)return null;
}
}
this.isEmpty=function(){//判断链表是否为空
return length==0;
}
this.mylength=function(){//返回链表长度
return length;
}
this.print=function(){
var current=head;
while(current){//打印整个链表
console.log(current.element);
current=current.next;
}
}
this.getHead=function(){//返回头结点
return head;
}
}
var link=new Link();
link.insert1('d');
link.insert2('e');
link.insert1('f');
link.insert1('g');
link.insert1('h');
link.remove2('d');
link.remove1();
console.log(link.mylength());
console.log(link.getHead());
link.print();