जब रिकर्सन विधि का उपयोग किए बिना किसी लिंक की गई सूची में किसी तत्व की खोज करना आवश्यक होता है, तो लिंक की गई सूची में मान जोड़ने की एक विधि, साथ ही लिंक की गई सूची के तत्वों को प्रदर्शित करने की एक विधि।
इसमें एक विधि भी होगी जो खोजे जा रहे तत्व के सूचकांक को खोजने में मदद करती है।
नीचे उसी के लिए एक प्रदर्शन है -
उदाहरण
class Node:
def __init__(self, data):
self.data = data
self.next = None
class my_linked_list:
def __init__(self):
self.head = None
self.last_node = None
def add_value(self, my_data):
if self.last_node is None:
self.head = Node(my_data)
self.last_node = self.head
else:
self.last_node.next = Node(my_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 find_index_val(self, my_key):
curr = self.head
index_val = 0
while curr:
if curr.data == my_key:
return index_val
curr = curr.next
index_val = index_val + 1
return -1
my_instance = my_linked_list()
my_list = [67, 4, 78, 98, 32, 0, 11, 8]
for data in my_list:
my_instance.add_value(data)
print('The linked list is : ')
my_instance.print_it()
print()
my_key = int(input('What value would you search for? '))
index_val = my_instance.find_index_val(my_key)
if index_val == -1:
print(str(my_key) + ' was not found.')
else:
print('Element was found at index ' + str(index_val) + '.')
n = int(input('How many elements would you wish to add ? '))
for i in range(n):
data = int(input('Enter data : '))
my_instance.add_value(data)
print('The linked list is : ')
my_instance.print_it() आउटपुट
The linked list is : 67 4 78 98 32 0 11 8 What value would you search for? 11 Element was found at index 6. How many elements would you wish to add ? 2 Enter data : 111 Enter data : 56 The linked list is : 67 4 78 98 32 0 11 8 111 56
स्पष्टीकरण
-
'नोड' वर्ग बनाया गया है।
-
आवश्यक विशेषताओं के साथ एक और 'my_linked_list' वर्ग बनाया गया है।
-
इसमें एक 'init' फ़ंक्शन होता है जिसका उपयोग पहले तत्व को प्रारंभ करने के लिए किया जाता है, यानी 'हेड' से 'कोई नहीं' और अंतिम नोड को 'कोई नहीं'।
-
'add_value' नाम की एक अन्य विधि को परिभाषित किया गया है, जिसका उपयोग लिंक की गई सूची में डेटा जोड़ने के लिए किया जाता है।
-
'प्रिंट_इट' नामक एक अन्य विधि को परिभाषित किया गया है जिसका उपयोग कंसोल पर लिंक्ड सूची डेटा प्रदर्शित करने के लिए किया जाता है।
-
'find_index_val' नाम की एक अन्य विधि परिभाषित की गई है जो उपयोगकर्ता द्वारा दर्ज किए गए तत्व के सूचकांक को खोजने में मदद करती है।
-
'my_linked_list' वर्ग का एक ऑब्जेक्ट बनाया जाता है।
-
एक सूची परिभाषित की गई है।
-
इस सूची को पुनरावृत्त किया गया है, और डेटा जोड़ने के लिए इस पर विधियों को बुलाया गया है।
-
यह 'print_it' पद्धति का उपयोग करके कंसोल पर प्रदर्शित होता है।
-
खोजे जाने वाले तत्व के लिए उपयोगकर्ता इनपुट पूछा जाता है।
-
इस पर 'find_index_val' पद्धति को कॉल किया जाता है, और आउटपुट कंसोल पर प्रदर्शित होता है।