Python 程序移除双向链表中的重复元素


当需要移除双向链表中的重复元素时,需要创建一个“节点”类。在这个类中,有三个属性:节点中存在的数据,对链表中下一个节点的访问权限,以及对链表中上一个节点的访问权限。

以下是相同内容的演示 -

示例

 在线演示

class Node:
   def __init__(self, my_data):
      self.previous = None
      self.data = my_data
      self.next = None
class double_list:
   def __init__(self):
      self.head = None
      self.tail = None
   def add_data(self, my_data):
      new_node = Node(my_data)
      if(self.head == None):
         self.head = self.tail = new_node
         self.head.previous = None
         self.tail.next = None
      else:
         self.tail.next = new_node
         new_node.previous = self.tail
         self.tail = new_node
         self.tail.next = None
   def print_it(self):
      curr = self.head
      if (self.head == None):
         print("The list is empty")
         return
      print("The nodes in the doubly linked list are :")
      while curr != None:
         print(curr.data)
         curr = curr.next
   def remove_duplicates(self):
      if(self.head == None):
         return
      else:
         curr = self.head;
         while(curr != None):
            index_val = curr.next
            while(index_val != None):
               if(curr.data == index_val.data):
                  temp = index_val
                  index_val.previous.next = index_val.next
                  if(index_val.next != None):
                     index_val.next.previous = index_val.previous
                  temp = None
               index_val = index_val.next
            curr = curr.next
my_instance = double_list()
print("Elements are being added to the doubly linked list")
my_instance.add_data(10)
my_instance.add_data(24)
my_instance.add_data(54)
my_instance.add_data(77)
my_instance.add_data(24)
my_instance.print_it()
print("The elements in the list after removing duplicates are : ")
my_instance.remove_duplicates()
my_instance.print_it()

输出

Elements are being added to the doubly linked list
The nodes in the doubly linked list are :
10
24
54
77
24
The elements in the list after removing duplicates are :
The nodes in the doubly linked list are :
10
24
54
77

解释

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

更新于: 2021-03-11

209 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.