जब दोहरी लिंक की गई सूची की शुरुआत में एक नया नोड सम्मिलित करने की आवश्यकता होती है, तो एक 'नोड' वर्ग बनाने की आवश्यकता होती है। इस वर्ग में, तीन विशेषताएं हैं, डेटा जो नोड में मौजूद है, लिंक की गई सूची के अगले नोड तक पहुंच और लिंक की गई सूची के पिछले नोड तक पहुंच है।
नीचे उसी के लिए एक प्रदर्शन है -
उदाहरण
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_start(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.previous = new_node
new_node.next = self.head
new_node.previous = None
self.head = new_node
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 beginning of doubly linked list")
my_instance.add_data_at_start(10)
my_instance.print_it()
my_instance.add_data_at_start(24)
my_instance.print_it()
my_instance.add_data_at_start(54)
my_instance.print_it()
my_instance.add_data_at_start(77)
my_instance.print_it()
my_instance.add_data_at_start(92)
my_instance.print_it() आउटपुट
Elements are being added to the beginning of doubly linked list The nodes in the doubly linked list are : 10 The nodes in the doubly linked list are : 24 10 The nodes in the doubly linked list are : 54 24 10 The nodes in the doubly linked list are : 77 54 24 10 The nodes in the doubly linked list are : 92 77 54 24 10
स्पष्टीकरण
- 'नोड' वर्ग बनाया गया है।
- आवश्यक विशेषताओं वाला एक और वर्ग बनाया गया है।
- 'add_data_at_start' नाम की एक विधि परिभाषित की गई है, जिसका उपयोग डबल लिंक की गई सूची की शुरुआत में डेटा जोड़ने के लिए किया जाता है।
- 'print_it' नाम की एक अन्य विधि परिभाषित की गई है, जो सर्कुलर लिंक्ड सूची के नोड्स को प्रदर्शित करती है।
- डबल_लिस्ट' वर्ग का एक ऑब्जेक्ट बनाया जाता है, और डबल लिंक्ड सूची की शुरुआत में डेटा जोड़ने के लिए उस पर विधियों को बुलाया जाता है।
- एक 'init' विधि को परिभाषित किया गया है, कि दोहरी लिंक की गई सूची के रूट, हेड और टेल नोड्स किसी से नहीं।
- सूची को पुनरावृत्त किया जाता है, और तत्व को डबल लिंक्ड सूची की शुरुआत में जोड़ा जाता है।
- यह 'print_it' पद्धति का उपयोग करके कंसोल पर प्रदर्शित होता है।