जब सिंगल लिंक्ड लिस्ट को सर्कुलर लिंक्ड लिस्ट में बदलने की आवश्यकता होती है, तो 'convert_to_circular_list' नाम की एक विधि परिभाषित की जाती है जो यह सुनिश्चित करती है कि अंतिम तत्व पहले तत्व की ओर इशारा करते हैं, जिससे यह प्रकृति में गोलाकार हो जाता है।
नीचे उसी का एक प्रदर्शन है -
उदाहरण
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList_struct:
def __init__(self):
self.head = None
self.last_node = None
def add_elements(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 convert_to_circular_list(my_list):
if my_list.last_node:
my_list.last_node.next = my_list.head
def last_node_points(my_list):
last = my_list.last_node
if last is None:
print('The list is empty...')
return
if last.next is None:
print('The last node points to None...')
else:
print('The last node points to element that has {}...'.format(last.next.data))
my_instance = LinkedList_struct()
my_input = input('Enter the elements of the linked list.. ').split()
for data in my_input:
my_instance.add_elements(int(data))
last_node_points(my_instance)
print('The linked list is being converted to a circular linked list...')
convert_to_circular_list(my_instance)
last_node_points(my_instance) आउटपुट
Enter the elements of the linked list.. 56 32 11 45 90 87 The last node points to None... The linked list is being converted to a circular linked list... The last node points to element that has 56...
स्पष्टीकरण
-
'नोड' वर्ग बनाया गया है।
-
आवश्यक विशेषताओं के साथ एक और 'LinkedList_struct' वर्ग बनाया गया है।
-
इसमें एक 'init' फ़ंक्शन होता है जिसका उपयोग पहले तत्व को प्रारंभ करने के लिए किया जाता है, यानी 'हेड' से 'कोई नहीं' और अंतिम नोड को 'कोई नहीं'।
-
'add_elements' नाम की एक अन्य विधि परिभाषित की गई है, जिसका उपयोग लिंक की गई सूची में पिछले नोड को लाने के लिए किया जाता है।
-
'convert_to_circular_list' नाम की एक अन्य विधि परिभाषित की गई है जो अंतिम नोड को पहले नोड की ओर इंगित करती है, जिससे यह प्रकृति में गोलाकार हो जाता है।
-
'last_node_points' नाम की एक विधि परिभाषित की गई है, जो जांचती है कि क्या सूची खाली है, या यदि अंतिम नोड 'कोई नहीं' को इंगित करता है, या यह लिंक की गई सूची के किसी विशिष्ट नोड को इंगित करता है।
-
'LinkedList_struct' वर्ग का एक ऑब्जेक्ट बनाया जाता है।
-
लिंक की गई सूची के तत्वों के लिए उपयोगकर्ता इनपुट लिया जाता है।
-
तत्वों को लिंक की गई सूची में जोड़ा जाता है।
-
इस लिंक की गई सूची में 'last_node_points' पद्धति को कहा जाता है।
-
प्रासंगिक आउटपुट कंसोल पर प्रदर्शित होता है।