เมื่อจำเป็นต้องค้นหาองค์ประกอบทั่วไปที่เกิดขึ้นเป็นครั้งแรกระหว่างสองรายการที่เชื่อมโยง วิธีการเพิ่มองค์ประกอบไปยังรายการที่เชื่อมโยง และวิธีการรับองค์ประกอบทั่วไปที่เกิดขึ้นเป็นครั้งแรกในรายการเชื่อมโยงเหล่านี้ถูกกำหนด .
ด้านล่างนี้เป็นการสาธิตสำหรับสิ่งเดียวกัน -
ตัวอย่าง
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
คำอธิบาย
-
สร้างคลาส "โหนด" แล้ว
-
'LinkedList_structure' คลาสอื่นพร้อมแอตทริบิวต์ที่จำเป็นจะถูกสร้างขึ้น
-
มีฟังก์ชัน 'init' ที่ใช้ในการเริ่มต้นองค์ประกอบแรก นั่นคือ 'head' เป็น 'None'
-
มีการกำหนดเมธอดชื่อ 'add_vals' ซึ่งช่วยเพิ่มมูลค่าให้กับสแต็ก
-
มีการกำหนดวิธีการอื่นที่ชื่อว่า 'first_common_val' ซึ่งจะช่วยค้นหาค่าทั่วไปแรกที่พบในสองรายการที่เชื่อมโยง
-
'LinkedList_structure' สองอินสแตนซ์ถูกสร้างขึ้น
-
เพิ่มองค์ประกอบลงในทั้งรายการที่เชื่อมโยง
-
วิธีการ 'first_common_value' ถูกเรียกในรายการที่เชื่อมโยงเหล่านี้
-
เอาต์พุตจะแสดงบนคอนโซล