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 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告