Python程式檢查兩個連結串列是否相同


當需要檢查兩個連結串列是否相同時,需要定義一個向連結串列新增元素的方法,以及一個檢查連結串列中元素相等性的方法。

以下是相同的演示 -

示例

class Node:
   def __init__(self, data):
      self.data = data
      self.next = None

class LinkedList_structure:
   def __init__(self):
      self.head = None
      self.last_node = None

   def add_vals(self, data):
      if self.last_node is None:
         self.head = Node(data)
         self.last_node = self.head
      else:
         self.last_node.next = Node(data)
         self.last_node = self.last_node.next

def check_equality(list_1, list_2):
   curr_1 = list_1.head
   curr_2 = list_2.head
   while (curr_1 and curr_2):
      if curr_1.data != curr_2.data:
         return False
      curr_1 = curr_1.next
      curr_2 = curr_2.next
   if curr_1 is None and curr_2 is None:
      return True
   else:
      return False

my_linked_list_1 = LinkedList_structure()
my_linked_list_2 = LinkedList_structure()

my_list = input('Enter the elements of the first linked list: ').split()
for elem in my_list:
   my_linked_list_1.add_vals(int(elem))

my_list = input('Enter the elements of the second linked list: ').split()
for elem in my_list:
   my_linked_list_2.add_vals(int(elem))

if check_equality(my_linked_list_1, my_linked_list_2):
   print('The two linked lists are the same')
else:
   print('The two linked list are not same')

輸出

Enter the elements of the first linked list: 34 56 89 12 45
Enter the elements of the second linked list: 57 23 78 0 2
The two linked list are not same

解釋

  • 建立了“Node”類。

  • 建立了另一個具有所需屬性的“LinkedList_structure”類。

  • 它有一個“init”函式,用於將第一個元素(即“head”)初始化為“None”,並將“last_node”初始化為“None”。

  • 定義了一個名為“add_vals”的方法,用於向棧新增值。

  • 定義了另一個名為“check_equality”的方法,用於檢查兩個連結串列中的元素是否相同。

  • 它根據相等性返回True或False。

  • 建立了兩個“LinkedList_structure”例項。

  • 元素被新增到兩個連結串列中。

  • 在這兩個連結串列上呼叫“check_equality”方法。

  • 輸出顯示在控制檯上。

更新於:2021年4月14日

218 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.