जब दोहरी लिंक की गई सूची के बीच में एक नया नोड डालने की आवश्यकता होती है, तो एक 'नोड' वर्ग बनाने की आवश्यकता होती है। इस वर्ग में, तीन विशेषताएं हैं, डेटा जो नोड में मौजूद है, लिंक की गई सूची के अगले नोड तक पहुंच और लिंक की गई सूची के पिछले नोड तक पहुंच है।
नीचे उसी के लिए एक प्रदर्शन है -
उदाहरण
class Node:
def __init__(self, my_data):
self.previous = None
self.data = my_data
self.next = None
class double_list:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def add_data(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
self.size = self.size + 1
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
def add_data_in_middle(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:
curr = self.head;
mid = (self.size//2) if(self.size % 2 == 0) else ((self.size+1)//2);
for i in range(1, mid):
curr = curr.next;
temp = curr.next;
temp.previous = curr;
curr.next = new_node;
new_node.previous = curr;
new_node.next = temp;
temp.previous = new_node;
self.size = self.size + 1;
my_instance = double_list()
print("Elements are being added to the doubly linked list")
my_instance.add_data(10)
my_instance.add_data(24)
my_instance.add_data(54)
print("Elements are added to the middle of the list")
my_instance.add_data_in_middle(77)
my_instance.print_it()
my_instance.add_data_in_middle(92)
my_instance.print_it() आउटपुट
Elements are being added to the doubly linked list Elements are added to the middle of the list The nodes in the doubly linked list are : 10 24 77 54 The nodes in the doubly linked list are : 10 24 92 77 54
स्पष्टीकरण
- 'नोड' वर्ग बनाया गया है।
- आवश्यक विशेषताओं वाला एक और वर्ग बनाया गया है।
- 'add_data_in_middle' नाम की एक विधि परिभाषित की गई है, जिसका उपयोग डबल लिंक्ड सूची के मध्य इंडेक्स में डेटा जोड़ने के लिए किया जाता है।
- 'add_data' नाम की एक विधि परिभाषित की गई है, जो डबल लिंक की गई सूची में नोड्स जोड़ने में मदद करती है।
- 'print_it' नाम की एक अन्य विधि परिभाषित की गई है, जो सर्कुलर लिंक्ड सूची के नोड्स को प्रदर्शित करती है।
- 'डबल_लिस्ट' वर्ग का एक ऑब्जेक्ट बनाया जाता है, और डबल लिंक्ड सूची में डेटा जोड़ने के लिए उस पर विधियों को बुलाया जाता है।
- 'add_data_in_middle' को लिंक की गई सूची के मध्य इंडेक्स में डेटा जोड़ने के लिए कहा जाता है।
- एक 'init' विधि को परिभाषित किया गया है, कि रूट, हेड, और टेल नोड्स डबल लिंक्ड लिस्ट का कोई नहीं से जुड़ा हुआ है।
- यह 'print_it' पद्धति का उपयोग करके कंसोल पर प्रदर्शित होता है।