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 first_common_val(list_1, list_2):
   curr_1 = list_1.head
   while curr_1:
      data = curr_1.data
      curr_2 = list_2.head
      while curr_2:
         if data == curr_2.data:
            return data
         curr_2 = curr_2.next
      curr_1 = curr_1.next
   return None

my_list_1 = LinkedList_structure()
my_list_2 = LinkedList_structure()

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

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

common_vals = first_common_val(my_list_1, my_list_2)

if common_vals:
   print('The element that is present first in the first linked list and is common to both is {}.'.format(common))
else:
   print('The two lists have no common elements')

輸出

Enter the elements of the first linked list : 45 67 89 123 45
Enter the elements of the second linked list : 34 56 78 99 0 11
The two lists have no common elements

解釋

  • 建立了“Node”類。

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

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

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

  • 定義了另一個名為“first_common_val”的方法,用於查詢在兩個連結串列中找到的第一個公共值。

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

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

  • 在這些連結串列上呼叫“first_common_value”方法。

  • 結果顯示在控制檯上。

更新於:2021年4月14日

199 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.