Python程序:移除循环链表中的重复元素


需要从循环链表中移除重复元素时,需要创建一个名为'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("The list is :")
   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
The list is :
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'方法在控制台中显示结果。

更新于:2021年3月13日

242 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.