//以下是一個鏈表類 function LinkedList(){ //Node表示要加入列表的項 var Node=function(element){ this.element=element; this.next=null; }; var length=0;//存儲列表項的數量 var hea ...
//以下是一個鏈表類
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());