जब दो लिंक्ड सूचियों में विशिष्ट स्थिति के संबंधित तत्वों को जोड़ने की आवश्यकता होती है, तो लिंक की गई सूची में तत्वों को जोड़ने की एक विधि, लिंक की गई सूची के तत्वों को प्रिंट करने की एक विधि, और एक लिंक की संबंधित स्थिति में तत्वों को जोड़ने की एक विधि सूची परिभाषित की गई है। दो सूचियाँ इंस्टेंस बनाए जाते हैं और इन लिंक्ड सूची इंस्टेंस पर पहले से परिभाषित विधि को कॉल किया जाता है।
नीचे उसी के लिए एक प्रदर्शन है -
उदाहरण
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 print_it(self):
curr = self.head
while curr is not None:
print(curr.data)
curr = curr.next
def add_linked_list(my_list_1, my_list_2):
sum_list = LinkedList_structure()
curr_1 = my_list_1.head
curr_2 = my_list_2.head
while (curr_1 and curr_2):
sum_val = curr_1.data + curr_2.data
sum_list.add_vals(sum_val)
curr_1 = curr_1.next
curr_2 = curr_2.next
if curr_1 is None:
while curr_2:
sum_list.add_vals(curr_2.data)
curr_2 = curr_2.next
else:
while curr_1:
sum_list.add_vals(curr_1.data)
curr_1 = curr_1.next
return sum_list
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))
sum_list = add_linked_list(my_list_1, my_list_2)
print('The sum of elements in the linked list is ')
sum_list.print_it() आउटपुट
Enter the elements of the first linked list : 56 34 78 99 54 11 Enter the elements of the second linked list : 23 56 99 0 122 344 The sum of elements in the linked list is 79 90 177 99 176 355
स्पष्टीकरण
-
'नोड' वर्ग बनाया गया है।
-
आवश्यक विशेषताओं के साथ एक और 'लिंक्डलिस्ट_स्ट्रक्चर' वर्ग बनाया गया है।
-
इसमें एक 'init' फंक्शन होता है जिसका इस्तेमाल पहले एलिमेंट यानी 'हेड' से 'कोई नहीं' को इनिशियलाइज़ करने के लिए किया जाता है।
-
'add_vals' नाम की एक विधि परिभाषित की गई है, जो स्टैक में मान जोड़ने में मदद करती है।
-
'प्रिंट_इट' नामक एक अन्य विधि को परिभाषित किया गया है, जो लिंक की गई सूची के मूल्यों को प्रदर्शित करने में मदद करती है।
-
'add_linked_list' नाम की एक अन्य विधि परिभाषित की गई है, जो दो लिंक की गई सूची के संबंधित तत्वों को जोड़ने में मदद करती है।
-
'LinkedList_struct' के दो उदाहरण बनाए गए हैं।
-
दोनों लिंक की गई सूचियों में तत्व जोड़े जाते हैं।
-
इन लिंक्ड सूचियों पर 'add_linked_list' पद्धति को कहा जाता है।
-
आउटपुट कंसोल पर प्रदर्शित होता है।