python/golang 删除链表中的元素
先用使用常规方法,两个指针:
golang实现:
typeNodestruct{
valueint
next*Node
}
typeLinkstruct{
head*Node
tail*Node
lenthint
}
//向链表中添加元素
func(link*Link)add(vint){
iflink.lenth==0{//当前链表是空链表
link.head=&Node{v,nil}
link.tail=link.head
link.lenth=1
}else{
newNond:=&Node{v,nil}
link.tail.next=newNond
link.tail=newNond
link.lenth+=1
}
}
//删除链表中的元素(双指针)
func(link*Link)remove(vint){
iflink.lenth==0{
fmt.Println("空链表,不支持该操作")
return
}
varprevious*Node=nil
forcurrent:=link.head;current!=nil;current=current.next{
ifcurrent.value==v{
ifcurrent==link.head{//要删除的是头节点
link.head=current.next
}elseifcurrent==link.tail{//要删除的是尾节点
previous.next=nil
link.tail=previous
}else{//要删除的是中间的节点
previous.next=current.next
}
link.lenth-=1
break
}
previous=current
}
}
//打印链表
func(link*Link)printList(){
iflink.lenth==0{
fmt.Println("空链表")
return
}
forcur:=link.head;cur!=nil;cur=cur.next{
fmt.Printf("%d",cur.value)
}
fmt.Println()
}
python实现:
classNode:
def__init__(self,value,next):
self.value=value
self.next=next
def__str__(self):
returnstr(self.value)
classLink:
def__init__(self):
self.head=None
self.tail=None
self.lenth=0
#向链表中添加元素
defadd(self,v):
ifself.lenth==0:#当前链表是空链表
self.head=Node(v,None)
self.tail=self.head
self.lenth=1
else:
new_node=Node(v,None)
self.tail.next=new_node
self.tail=new_node
self.lenth+=1
#打印链表
defprint(self):
ifself.lenth==0:
print('空链表')
return
cur=self.head
whileTrue:
ifcur==None:
print()
break
print(cur,end='')
cur=cur.next
#删除链表中的元素
defremove(self,v):
ifself.lenth==0:
return
cur=self.head
pre=None
whileTrue:
ifcur.value==v:
ifcur==self.head:#要删除的是头节点
self.head=cur.next
elifcur==self.tail:#要删除的是尾节点
pre.next=None
self.tail=pre
else:#要删除的是中间的节点
pre.next=cur.next
self.lenth-=1
break
pre=cur
cur=cur.next
ifcur==None:
print("未找到",v)
break
只使用使用一个指针实现链表的删除:
golang实现:
func(link*Link)remove_with_one_pointer(vint){
iflink.lenth==0{
return
}
iflink.tail.value==v{//要删除的节点是尾节点,需特殊处理
iflink.lenth==1{//如果链表只有一个节点
link.head=nil
link.tail=nil
}else{//大于一个节点
cur:=link.head
for;cur.next.next!=nil;cur=cur.next{
}//找到尾节点的前一个节点
cur.next=nil
link.tail=cur
}
link.lenth-=1
return
}
//要删除的节点在头部/中间的常规情况
forcur:=link.head;cur!=nil;cur=cur.next{
ifcur.value==v{
cur.value=cur.next.value
cur.next=cur.next.next
link.lenth-=1
return
}
}
fmt.Println("未找到",v)
}
python实现:
defremove_with_one_pointer(self,v):
ifself.lenth==0:
return
ifself.tail.value==v:#要删除的节点是尾节点,需特殊处理
ifself.lenth==1:#如果链表只有一个节点
self.head=None
self.tail=None
else:#大于一个节点
cur=self.head
whileTrue:
ifcur.next.nextisNone:#找到尾节点的前一个节点
break
else:
cur=cur.next
cur.next=None
self.tail=cur
self.lenth-=1
return
#要删除的节点在头部/中间的常规情况
cur=self.head
whileTrue:
ifcur.value==v:
cur.value=cur.next.value
cur.next=cur.next.next
self.lenth-=1
break
cur=cur.next
ifcurisNone:
print('未找到',v)
break
以上就是python/golang删除链表中的元素的详细内容,更多关于python/golang链表的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。