To insert an element in a doubly linked list, we first need to create a list:
class Nodeq:def __init__(self, data):self.data = dataself.next = Noneself.prev = None
There are three ways of inserting an element into a doubly linked list:
insert_beginning
insert_end
insert_after
Insert beginning is a method to include a new_node
in front of the head node and represent new_node
as the new head node.
def insert_beginning(self,data):new_node = Nodeq(data)#creating a node with the given dataif(self.head == None):self.head = new_node;returnself.head.prev = new_nodenew_node.next = self.headself.head = new_node#making the new_node as the new head node
With the help of insert_end
, we can insert elements at the end of the doubly linked list.
def insert_end(self, new_data):new_node = Nodeq(new_data)if self.head is None:#checking if the DLL existsnew_node.prev = Noneself.head = new_nodereturnlast = self.headwhile last.next:#to asigning the last node to the "last"last = last.nextlast.next = new_nodenew_node.prev = last#inserting the new node at the end of the DLLreturn
With the help of insert_after
we can insert after a given element.
prev_data
is the given element.
def insert_after(self, prev_data, data):h=self.headwhile h:#searching for the given dataif prev_data == h.data:breakh=h.nextif h is None:print("The previous data is not present in the DLL")returnnew_node = Nodeq(data)# the new_node is inserted after the given nodenew_node.next= h.nexth.next=new_nodereturn
To print the elements in doubly linked list we use Count_Display
method.
def Count_Display(self):if self.head==None: # to check if DLL existsprint("We need a DLL to print")returntemp = self.headcount=0while temp:print (temp.data)#printing node datacount+=1temp = temp.nextreturn count
The final code for the insertion of elements in the Doubly Linked List is shown below.
class Nodeq:def __init__(self, data):self.data = dataself.next = Noneself.prev = Noneclass DoublyLinkedList:def __init__(self):self.head = Nonedef Count_Display(self):if self.head==None:print("We need a DLL to print")returntemp = self.headcount=0while temp:print (temp.data)count+=1temp = temp.nextreturn countdef insert_begining(self,data):new_node = Nodeq(data)if(self.head == None):self.head = new_nodereturnself.head.prev = new_nodenew_node.next = self.headself.head = new_nodedef insert_end(self, new_data):new_node = Nodeq(new_data)if self.head is None:new_node.prev = Noneself.head = new_nodereturnlast = self.headwhile last.next:last = last.nextlast.next = new_nodenew_node.prev = lastreturndef insert_after(self, prev_data, data):h=self.headwhile h:if prev_data == h.data:breakh=h.nextif h is None:print("The previous Node data must be in the DLL")returnnew_node = Nodeq(data)new_node.next= h.nexth.next=new_nodereturnDllist = DoublyLinkedList()Dllist.insert_end(2)Dllist.insert_begining(3)Dllist.insert_begining(4)Dllist.insert_end(5)Dllist.insert_after(2,0)print("The number of elements in the DLL list are :",Dllist.Count_Display())