जब दो लिंक्ड सूचियों के बीच पहली बार होने वाले सामान्य तत्व को खोजने की आवश्यकता होती है, तो लिंक की गई सूची में तत्वों को जोड़ने की एक विधि और इन लिंक्ड सूचियों में पहली बार होने वाले सामान्य तत्व को प्राप्त करने की एक विधि परिभाषित की जाती है। ।
नीचे उसी के लिए एक प्रदर्शन है -
उदाहरण
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
स्पष्टीकरण
-
'नोड' वर्ग बनाया गया है।
-
आवश्यक विशेषताओं के साथ एक और 'लिंक्डलिस्ट_स्ट्रक्चर' वर्ग बनाया गया है।
-
इसमें एक 'init' फंक्शन होता है जिसका इस्तेमाल पहले एलिमेंट यानी 'हेड' से 'कोई नहीं' को इनिशियलाइज़ करने के लिए किया जाता है।
-
'add_vals' नाम की एक विधि परिभाषित की गई है, जो स्टैक में मान जोड़ने में मदद करती है।
-
'first_common_val' नाम की एक अन्य विधि परिभाषित की गई है, जो दो लिंक्ड सूचियों में पाए गए पहले सामान्य मान को खोजने में मदद करती है।
-
'LinkedList_struct' के दो उदाहरण बनाए गए हैं।
-
दोनों लिंक की गई सूचियों में तत्व जोड़े जाते हैं।
-
इन लिंक्ड सूचियों पर 'first_common_value' पद्धति को कहा जाता है।
-
आउटपुट कंसोल पर प्रदर्शित होता है।