单向链表
1.单向链表的封装
单链表跟双向链表一样,js里的引用类型有点不太懂,此处的this.head不知道是看做指针还是头结点来使用。
我在这里是把this.head复制了一个节点数据,同时把this.head的看做了指针指向了第一个新节点(不这样想看不下去了),按我的想法插入第一个节点的时候是 this.head.next=newNode.先记录一下这个知识懵点。
暂时没
function Node(data){
this.data=data;
this.next=null
}
// 属性
this.head=null
this.length=0;
2.向尾部加入一个节点
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
}
// 最后节点的next指向新的节点
current.next=newNode
}
this.length+=1
}
3.读出字符串
LinkedList.prototype.toString=function(){
var current=this.head;
var listString=""
while(current){
listString+=current.data+" "
current=current.next
}
return listString
}
4.获取某个数据值
LinkedList.prototype.get=function(position){
if(position<0||position>=this.length) return null
var current=this.head
var index=0
while(index++<position){
current=current.next
}
return current.data
}
5.是否存在值
LinkedList.prototype.indexOf=function(data){
var current=this.head
var index=0
while(current){
if(current.data=data){
return inddex
}
current=current.nextindex+=1
}
return -1
}
6.更新值
LinkedList.prototype.update=function(position,newData){
if(position<0||position>=this.length)return false
var current=this.head
var index=0
while(index++<position){
current=current.next
}
current.data=newData
return true
}
7.删除数据
LinkedList.prototype.removeAt=function(position){
if(position<0||position>=this.length)return null
var current=this.head
if(position==0)
{
this.head=this.head.next
} else {
var index=0
var previous=null
while(index++<position){
previous=current
current=current.next
}
previous.next=current.next
}
this.length-=1
return current.data
}
LinkedList.prototype.remove=function(data){
var position=this.indexOf(data)
return this.removeAt(position)
}