在循环链表末尾插入新节点的Python程序!
当需要在循环链表的末尾插入一个新节点时,需要创建一个'Node'类。在这个类中,有两个属性,节点中存在的数据,以及对链表下一个节点的访问。
在循环链表中,头部和尾部彼此相邻。它们连接形成一个圆圈,并且在最后一个节点中没有'NULL'值。
需要创建另一个具有初始化函数的类,并且节点的头部将被初始化为“无”。
用户定义了多种方法在链表的末尾添加节点,并打印节点值。
以下是相同的演示-
示例
class Node: def __init__(self,data): self.data= data self.next= None class list_creation: def __init__(self): self.head= Node(None) self.tail= Node(None) self.head.next =self.tail self.tail.next =self.head def add_at_end(self,my_data): new_node = Node(my_data) if self.head.data is None: self.head = new_node self.tail = new_node new_node.next =self.head else: self.tail.next = new_node self.tail = new_node self.tail.next = self.head def print_it(self): curr = self.head; ifself.headis None: print("The list is empty"); return; else: print(curr.data) while(curr.next != self.head): curr = curr.next; print(curr.data) print("\n"); class circular_linked_list: my_cl = list_creation() print("Nodes are being added to end of list") my_cl.add_at_end(21); my_cl.print_it(); my_cl.add_at_end(53); my_cl.print_it(); my_cl.add_at_end(76); my_cl.print_it();输出结果
Nodes are being added to end of list 21 21 53 21 53 76
解释
创建了“节点”类。
创建了另一个具有必需属性的类。
定义了另一个名为“add_at_end”的方法,用于将数据添加到i.e“尾”节点之后的循环链表的末尾。
定义了另一个名为“print_it”的方法,它显示循环链表的节点。
创建“list_creation”类的对象,并在其上调用方法以添加数据。
定义了一个'init'方法,即循环链表的第一个和最后一个节点为None。
'add_at_end'方法被调用。
它获取链表的尾部,在其后添加一个元素,并将其地址引用到头指针和前一个指针。
这使用“print_it”方法显示在控制台上。