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  

   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

   def remove_duplicate_vals(self):  
      curr = self.head
      if(self.head == None):
         print("The list is empty")
      else:
         while(True):
            temp = curr
            index_val = curr.next
            while(index_val != self.head):
               if(curr.data == index_val.data):
                  temp.next = index_val.next
                else:
                  temp = index_val
             index_val= index_val.next
            curr =curr.next
            if(curr.next == self.head):
               break;        
   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)
   my_cl.add_data(21)
   print("列表为:")
   my_cl.print_it();  
   my_cl.remove_duplicate_vals()
   print("The updated list is :")
   my_cl.print_it(); 

输出

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

The updated list is :
21
54
78
99

解释

  • 创建 'Node' 类。
  • 创建具有所需属性的另一个类。
  • 定义另一个名为 'remove_duplicate_vals' 的方法,用于删除链接列表中存在的重复元素。
  • 定义另一个名为 'print_it' 的方法,显示循环链接列表的节点。
  • 创建 'list_creation' 类的对象,并调用其方法来添加数据。
  • 定义一个 'init' 方法,将循环链接列表的第一个和最后一个节点设置为 None。
  • 'remove_duplicate_vals'方法被调用。
  • 它遍历列表,并检查是否有任何元素重复。
  • 如果是,则删除它。
  • 使用"print_it"方法将其显示在控制台上。

相关文章