<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function LinkedList(){
this.head=null
this.length=0
}
function Node(data){
this.data=data
this.next=null
}
//链表中添加节点
LinkedList.prototype.append=function(data){
var newNode= new Node(data)
if(this.length===0){
this.head=newNode
}else{
var current =this.head
while(current.next){
current=current.next
}
current.next=newNode
}
this.length++
}
//insert插入节点
LinkedList.prototype.insert=function(data,position){
if(position<0||position>this.length){
return false
}
var newNode= new Node(data)
if(position===0){
newNode.next=this.head
this.head=newNode
}else{
var index=0
var current=this.head
var previous=null
while(index++<position){
previous=current
current=current.next
}
newNode.next=current
previous.next=newNode
}
this.length++
return true
}
//get方法
LinkedList.prototype.get=function(position){
if(position<0||position>=this.length){
return null
}
var current=this.head
var index=0
while(index<position){
index++
current=current.next
}
return current.data
}
//indexOf方法
LinkedList.prototype.indexOf=function(data){
var current=this.head
var index=0
while(current){
if(current.data==data){
return index
}
current=current.next
index++
}
return -1
}
//update方法
LinkedList.prototype.update=function(position,data){
if(position<0||position>=this.length){
return false
}
var current=this.head
var index=0
while(index++<position){
current=current.next
}
current.data=data
return true
}
//romoveAt方法
LinkedList.prototype.removeAt=function(position){
if(position<0||position>=this.length) return false;
if(position==0){
this.head=this.head.next
}else{
var index=0
var current=this.head
var previous=null
while(index++<position){
previous=current
current=current.next
}
previous.next=current.next
}
this.length--
return true
}
//isEmpty方法
LinkedList.prototype.isEmpty=function(){
return this.length==0
}
//size方法
LinkedList.prototype.size=function(){
return this.length
}
//toString方法
LinkedList.prototype.toString=function(){
var current=this.head
var listString=""
while(current){
listString+=current.data+''
current=current.next
}
return listString
}
//测试代码
var list =new LinkedList()
list.append('a')
list.append('b')
list.append('c')
list.append('d')
list.insert('aa',1)
console.log(list.get(0))
list.update(2,'bb')
console.log(list)
console.log(list.indexOf('aa'))
console.log(list.isEmpty())
console.log(list.size())
</script>
</body>
</html>