Python与Go语言实现循环链表详解
本文详细解析循环链表的定义及其与单链表在增删操作上的细微差别,重点介绍了Python和Go语言的具体代码实现。内容涵盖空链表、单节点及头尾节点删除等特殊场景的处理逻辑,并提供完整的可运行示例代码,帮助开发者深入理解循环链表的构建与维护。
循环链表定义与操作要点
循环链表是一种将单链表末尾节点指向头部节点,从而形成闭环结构的数据结构。其增加和删除节点的操作逻辑与单链表基本一致,但在具体实现时需特别注意几种边界情况:在增加节点时,需处理向空链表添加第一个节点的特殊场景;在删除节点时,则需考虑被删除节点是否为头节点或尾节点,以及链表中仅包含一个节点时的特殊处理。
Go语言实现代码
以下是使用Go语言实现的循环链表代码示例:
type Node struct {
value int
next *Node
}
type Circle struct {
tail *Node
lenth int
}
// 增加节点:
func (c *Circle) add(value int) {
newNode := &Node{value, nil}
if c.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(v int) {
if c.lenth == 0 {
fmt.Println("空环")
return
} else if c.lenth == 1 && c.tail.value == v { //链表中只有一个节点的特殊情况
c.tail = nil
c.lenth = 0
c.printCircle()
return
}
pre := c.tail
cur := c.tail.next // 头节点
for i := 0; i < c.lenth; i++ {
if cur.value == v {
if cur == c.tail { //如果删除的节点是尾节点,需更新tail
c.tail = pre
}
pre.next = cur.next
c.lenth -= 1
c.printCircle()
return
}
pre = cur
cur = cur.next
}
fmt.Println(v, "不在环中")
}
//打印节点:
func (c *Circle) printCircle() {
if c.lenth == 0 {
fmt.Println("空环")
return
}
cur := c.tail.next // 头节点
for i := 0; i < c.lenth; i++ {
fmt.Printf("%d ", cur.value)
cur = cur.next
}
fmt.Println()
}
func testCircle() {
var circle *Circle = new(Circle)
//for i := 1; i <=41; i++ {
// circle.add(i)
//}
circle.add(1)
circle.remove(10)
circle.printCircle()
}
Python语言实现代码
以下是使用Python语言实现的循环链表代码示例:
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def __str__(self):
return str(self.value)
class Circle:
def __init__(self):
self.tail = None
self.lenth = 0
# 增加节点
def add(self, v):
new_node = Node(v)
if self.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
# 删除节点
def remove(self, v):
if self.lenth == 0:
print("空环")
return
elif self.lenth == 1 and self.tail.value == v: # 链表中只有一个节点的特殊情况
self.tail = None
self.lenth = 0
return
pre = self.tail
cur = self.tail.next # 头节点
for i in range(self.lenth):
if cur.value == v:
if cur == self.tail: # 如果删除的节点是尾节点,需更新tail
self.tail = pre
pre.next = cur.next
self.lenth -= 1
return
pre = cur
cur = cur.next
print(v, "不在环中")
# 打印链表
def print_circle(self):
if self.lenth == 0:
print('空环')
return
cur = self.tail.next # 头节点
for i in range(self.lenth):
print(cur, end=" ")
cur = cur.next
print()
def test():
c = Circle()
for i in range(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和Go语言实现循环链表的完整示例。如需了解更多相关技术细节,请持续关注本站发布的其他文章。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









