Python循环链表程序
当需要创建一个生成链表的 Python 程序时,需要创建一个“节点”类。为了显示循环列表中的数据元素,可以定义另一个方法,该方法将显示数据。在这个类中,有两个属性,节点中存在的数据,以及对链表下一个节点的访问。在循环链表中,头部和尾部彼此相邻。它们连接成一个圆圈,并且最后一个节点没有“NULL”值。
还需要创建另一个“linked_list”类,该类将具有初始化函数,并且节点的头部将初始化为“None”。
以下是相同内容的演示 -
示例
class Node: def __init__(self, my_data): self.data = my_data self.next = None class circularLinkedList: def __init__(self): self.head = None def add_data(self, my_data): ptr_1 = Node(my_data) temp = self.head ptr_1.next = self.head if self.head is not None: while(temp.next != self.head): temp = temp.next temp.next = ptr_1 else: ptr_1.next = ptr_1 self.head = ptr_1 def print_it(self): temp = self.head if self.head is not None: while(True): print("%d" %(temp.data)), temp = temp.next if (temp == self.head): break my_list = circularLinkedList() print("Elements are added to the list ") my_list.add_data (56) my_list.add_data (78) my_list.add_data (12) print("The data is : ") my_list.print_it()
输出
Elements are added to the list The data is : 12 78 56
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
解释
- 创建“节点”类。
- 创建另一个具有所需属性的“circularLinkedList”类。
- 它有一个“init”函数,用于初始化第一个元素,即“head”为“None”。
- 定义了另一个名为“add_data”的方法,用于向循环链表添加数据。
- 定义了另一个名为“print_it”的方法,用于在控制台上显示链表数据。
- 创建“linked_list”类的对象,并在其上调用方法以添加数据。
- 使用“print_it”方法在控制台上显示此内容。
广告