function LinkedList(){
this.length=0;
this.head=null;
}
function Node(data){
this.data=data;
this.next=null;
}
//添加
LinkedList.prototype.append=function(data){
var node=new Node(data);
if(this.length===0){
this.head=node;
}else{
var current=this.head;
while(current.next){
current=current.next;
}
current.next=node;
}
this.length+=1;
}
//输出
LinkedList.prototype.toString=function(){
var current=this.head;
var str='';
while(current){
str+=current.data+' ';
current=current.next;
}
return str;
}
//插入
LinkedList.prototype.insert=function(position,data){
if(position<0||position>this.length)return false;
var node=new Node(data);
if(position===0){
node.next=this.head.next;
this.head.next=node;
}else{
var current=this.head;
var previous=null;
var index=0;
while(index++<position){
previous=current;
current=current.next;
index++;
}
node.next=current;
previous.next=node;
this.length++;
}
}
//获取元素
LinkedList.prototype.get=function(position){
if(position<0||position>this.length-1)return false;
var index=0;
var current=this.head;
while(index<position){
current=current.next;
index++;
}
return current.data;
}
var list=new LinkedList();
//修改元素
LinkedList.prototype.update=function(position,data){
if(position<0||position>this.length-1)return false;
var index=0;
var current=this.head;
while(index<position){
current=current.next;
index++;
}
current.data=data;
return true;
}
//删除元素
LinkedList.prototype.removeAt=function(position){
if(position<0||position>this.length-1)return false;
if(this.head==null){
return null;
}
var index=0;
var previous=null;
var current=this.head;
while(index<position){
previous=current;
current=current.next;
index++;
}
previous.next=current.next;
this.length--;
}
//查找元素下标
LinkedList.prototype.indexOf=function(data){
if(this.length===0)return -1;
var index=0;
var current=this.head;
while(current&¤t.data!==data){
current=current.next;
index++
}
if(current==null)return -1;
return index;
}
//移除最后一个元素
LinkedList.prototype.remove=function(){
if(!this.head)return false;
var index=0;
var current=this.head;
var previous=null;
while (index<this.length-1){
previous=current;
current=current.next;
index++;
}
previous.next=null;
this.length--;
}