在循环链表中间插入新节点的 Python 程序

pythonserver side programmingprogramming

当需要在循环链表中间插入新节点时,需要创建一个"Node"类。在这个类中,有两个属性,节点中存在的数据和对链表下一个节点的访问。

在循环链表中,头部和尾部彼此相邻。它们连接起来形成一个圆圈,最后一个节点没有"NULL"值。

需要创建另一个具有初始化函数的类,并且节点的头部将被初始化为"None"。 

用户定义多种方法在链表之间添加节点,并打印节点值。

下面是同样的演示 −

示例

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  
      self.size = 0;  

   def add_data(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
      self.size = self.size+1

   def add_in_between(self,my_data):  
      new_node = Node(my_data);  
      if(self.head == None):  
         self.head = new_node;  
         self.tail = new_node;  
         new_node.next = self.head;  
      else:  
         count = (self.size//2) if (self.size % 2 == 0) else ((self.size+1)//2);  
         temp = self.head;  
         for i in range(0,count):  
            curr = temp;  
            temp = temp.next;  
         curr.next = new_node;  
         new_node.next = temp;  
      self.size = self.size+1;
         
   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 the list")
   my_cl.add_data(21)
   my_cl.add_data(54)
   my_cl.add_data(78)
   my_cl.add_data(99)
   print("列表为:")
   my_cl.print_it();  
   my_cl.add_in_between(33);
   print("The updated list is :")
   my_cl.print_it();  
   my_cl.add_in_between(56);
   print("The updated list is :")
   my_cl.print_it();  
   my_cl.add_in_between(0);
   print("The updated list is :")
   my_cl.print_it();   

输出

Nodes are being added to the list
列表为:
21
54
78
99

The updated list is :
21
54
33
78
99

The updated list is :
21
54
33
56
78
99

The updated list is :
21
54
33
0
56
78
99

解释

  • 创建 'Node' 类。
  • 创建另一个具有所需属性的类。
  • 定义另一个名为 'add_in_between' 的方法,用于将数据添加到中间的循环链表,即最中间的位置。
  • 定义另一个名为 'print_it' 的方法,显示循环链表的节点。
  • 创建 'list_creation' 类的对象,并调用其方法来添加数据。
  • 定义一个 'init' 方法,将循环链表的第一个和最后一个节点设置为 None。
  • 'add_in_between'方法被调用。
  • 它遍历列表,获取最中间的索引并将元素插入此位置。
  • 使用"print_it"方法将其显示在控制台上。

相关文章