Python 程序在循环链表末尾插入新节点


当需要在循环链表末尾插入新节点时,需要创建一个“节点”类。在这个类中,有两个属性,节点中存在的数据,以及对链表下一个节点的访问。

在循环链表中,头和尾彼此相邻。它们连接形成一个圆圈,并且最后一个节点没有“空”值。

需要创建另一个类,该类将具有初始化函数,并且节点的头将初始化为“无”。

用户定义了多个方法,用于在链表末尾添加节点以及打印节点值。

以下是相同内容的演示 -

示例

在线演示

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;  
      if self.head is 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”的方法,用于在末尾(即“尾”节点之后)向循环链表添加数据。
  • 定义了另一个名为“print_it”的方法,用于显示循环链表的节点。
  • 创建“list_creation”类的对象,并在其上调用方法以添加数据。
  • 定义了一个“init”方法,将循环链表的第一个和最后一个节点设置为无。
  • 调用“add_at_end”方法。
  • 它获取链表的尾部,在其后添加一个元素,并将它的地址引用到头指针和前一个指针。
  • 使用“print_it”方法在控制台上显示此内容。

更新于:2021年3月13日

380 次浏览

开启您的职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.