Python程序添加新节点到循环链表末尾
循环链表是一种链表,其尾节点连接到头节点,形成一个环。在Python中,可以使用类和对象来创建循环链表。本文将介绍如何使用Python程序添加新节点到循环链表末尾。
更多Python相关文章,请阅读:Python 教程
创建循环链表
首先,定义一个节点类,如下所示:
class Node:
def __init__(self, data):
self.data = data
self.next = None
其中,节点有两个属性:data表示节点数据,next是指针,指向下一个节点。
接下来,创建循环链表类,如下所示:
class CircularLinkedList:
def __init__(self):
self.head = None
其中,循环链表有一个属性:head表示链表头节点。
然后,定义一个方法用于在循环链表末尾添加新节点:
def add_node(self, data):
# Create a new node
new_node = Node(data)
# Check if the list is empty
if self.head is None:
# Make this the head node
self.head = new_node
# Set the head's next to itself to form a loop
self.head.next = self.head
else:
# Find the last node
current_node = self.head
while current_node.next != self.head:
current_node = current_node.next
# Insert the new node at the end
current_node.next = new_node
# Set the new node's next to the head to form a loop
new_node.next = self.head
在这个方法中,先创建一个新节点,然后检查链表是否为空。如果链表为空,将新节点设置为头节点,并将头节点的next属性设置为它自己,以形成一个循环链表。如果链表不为空,则遍历链表,找到最后一个节点,并将新节点插入到末尾,将新节点的next属性设置为头节点,以形成一个循环链表。
测试添加新节点的代码
为了测试添加新节点的代码,可以创建一个循环链表,然后添加一些新节点。以下是示例代码:
# Create a new circular linked list
circular_linked_list = CircularLinkedList()
# Add some nodes to the list
circular_linked_list.add_node(1)
circular_linked_list.add_node(2)
circular_linked_list.add_node(3)
这段代码首先创建一个循环链表对象,然后添加三个新节点。
完整代码
以下是完整的Python代码,包括节点类、循环链表类和添加新节点的方法:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
def add_node(self, data):
# Create a new node
new_node = Node(data)
# Check if the list is empty
if self.head is None:
# Make this the head node
self.head = new_node
# Set the head's next to itself to form a loop
self.head.next = self.head
else:
# Find the last node
current_node = self.head
while current_node.next != self.head:
current_node = current_node.next
# Insert the new node at the end
current_node.next = new_node
# Set the new node's next to the head to form a loop
new_node.next = self.head
# Test the code
circular_linked_list = CircularLinkedList()
circular_linked_list.add_node(1)
circular_linked_list.add_node(2)
circular_linked_list.add_node(3)
结论
本文介绍了如何使用Python程序添加新节点到循环链表末尾。首先,定义了一个节点类和循环链表类,然后介绍了如何添加新节点的方法。最后,提供了一个完整的示例代码,展示如何创建循环链表和添加新节点。