python/golang实现循环链表的示例代码
循环链表就是将单链表的末尾指向其头部,形成一个环。循环链表的增删操作和单链表的增删操作
区别不大。只是增加时,需要考虑空链表增加第一个节点的特殊情况;删除时需考虑删除节点是头/尾节点,和链表中只有一个节点的特殊情况。
golang实现:
typeNodestruct{
valueint
next*Node
}
typeCirclestruct{
tail*Node
lenthint
}
//增加节点:
func(c*Circle)add(valueint){
newNode:=&Node{value,nil}
ifc.lenth==0{//空链表中添加节点
c.tail=newNode
c.tail.next=newNode
}else{
newNode.next=c.tail.next
c.tail.next=newNode
c.tail=newNode
}
c.lenth+=1
c.printCircle()
}
//删除节点:
func(c*Circle)remove(vint){
ifc.lenth==0{
fmt.Println("空环")
return
}elseifc.lenth==1&&c.tail.value==v{//链表中只有一个节点的特殊情况
c.tail=nil
c.lenth=0
c.printCircle()
return
}
pre:=c.tail
cur:=c.tail.next//头节点
fori:=0;i
python实现:
classNode:
def__init__(self,value,next=None):
self.value=value
self.next=next
def__str__(self):
returnstr(self.value)
classCircle:
def__init__(self):
self.tail=None
self.lenth=0
#增加节点
defadd(self,v):
new_node=Node(v)
ifself.lenth==0:#空链表中添加节点
self.tail=new_node
self.tail.next=new_node
else:
new_node.next=self.tail.next
self.tail.next=new_node
self.tail=new_node
self.lenth+=1
#删除节点
defremove(self,v):
ifself.lenth==0:
print("空环")
return
elifself.lenth==1andself.tail.value==v:#链表中只有一个节点的特殊情况
self.tail=None
self.lenth=0
return
pre=self.tail
cur=self.tail.next#头节点
foriinrange(self.lenth):
ifcur.value==v:
ifcur==self.tail:#如果删除的节点是尾节点,需更新tail
self.tail=pre
pre.next=cur.next
self.lenth-=1
return
pre=cur
cur=cur.next
print(v,"不在环中")
#打印链表
defprint_circle(self):
ifself.lenth==0:
print('空环')
return
cur=self.tail.next#头节点
foriinrange(self.lenth):
print(cur,end="")
cur=cur.next
print()
deftest():
c=Circle()
foriinrange(10):
c.add(i)
c.print_circle()
c.remove(0)
c.print_circle()
c.remove(10)
c.print_circle()
c.remove(9)
c.print_circle()
c.remove(4)
c.print_circle()
以上就是python/golang实现循环链表的示例代码的详细内容,更多关于python/golang循环链表的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。