जब दोहरी लिंक की गई सूची के अंत में एक नया नोड सम्मिलित करने की आवश्यकता होती है, तो एक 'नोड' वर्ग बनाने की आवश्यकता होती है। इस वर्ग में, तीन विशेषताएं हैं, डेटा जो नोड में मौजूद है, लिंक की गई सूची के अगले नोड तक पहुंच और लिंक की गई सूची के पिछले नोड तक पहुंच है।
नीचे उसी के लिए एक प्रदर्शन है -
उदाहरण
class Node:
def __init__(self, my_data):
self.prev = None
self.data = my_data
self.next = None
class double_list:
def __init__(self):
self.head = None
self.tail = None
def add_data_at_end(self, my_data):
new_node = Node(my_data)
if(self.head == None):
self.head = self.tail = new_node
self.head.previous = None
self.tail.next = None
else:
self.tail.next = new_node
new_node.previous = self.tail
self.tail = new_node
self.tail.next = None
def print_it(self):
curr = self.head
if (self.head == None):
print("The list is empty")
return
print("The nodes in the doubly linked list are :")
while curr != None:
print(curr.data)
curr = curr.next
my_instance = double_list()
print("Elements are being added to the end of doubly linked list")
my_instance.add_data_at_end(10)
my_instance.print_it()
my_instance.add_data_at_end(24)
my_instance.print_it()
my_instance.add_data_at_end(54)
my_instance.print_it()
my_instance.add_data_at_end(77)
my_instance.print_it()
my_instance.add_data_at_end(92)
my_instance.print_it() आउटपुट
Elements are being added to the end of doubly linked list The nodes in the doubly linked list are : 10 The nodes in the doubly linked list are : 10 24 The nodes in the doubly linked list are : 10 24 54 The nodes in the doubly linked list are : 10 24 54 77 The nodes in the doubly linked list are : 10 24 54 77 92
स्पष्टीकरण
- 'नोड' वर्ग बनाया गया है।
- आवश्यक विशेषताओं वाला एक और वर्ग बनाया गया है।
- 'add_data_at_end' नाम की एक विधि परिभाषित की गई है, जिसका उपयोग डबल लिंक्ड सूची के अंत में डेटा जोड़ने के लिए किया जाता है।
- 'print_it' नाम की एक अन्य विधि परिभाषित की गई है, जो सर्कुलर लिंक्ड सूची के नोड्स को प्रदर्शित करती है।
- 'डबल_लिस्ट' वर्ग का एक ऑब्जेक्ट बनाया जाता है, और डबल लिंक्ड सूची के अंत में डेटा जोड़ने के लिए उस पर विधियों को बुलाया जाता है।
- एक 'init' विधि को परिभाषित किया गया है, कि रूट, हेड, और टेल नोड्स डबल लिंक्ड लिस्ट का कोई नहीं से जुड़ा हुआ है।
- सूची को पुनरावृत्त किया जाता है, और तत्व को दोगुनी लिंक की गई सूची के अंत में जोड़ा जाता है।
- यह 'print_it' पद्धति का उपयोग करके कंसोल पर प्रदर्शित होता है।