Linked lists are used in various applications in python programming. In this article, we will implement a doubly linked list in python. To understand doubly linked lists, you will need to have the knowledge of simple linked lists. Therefore, if you don’t know about singly linked lists, you can read about them in this article on linked lists in python.
- What Is a Doubly Linked List?
- How to Create a Doubly Linked List in Python?
- Check if a Doubly Linked List Is Empty in Python
- Find the Length of a Doubly Linked List in Python
- Search an Element in a Doubly Linked List in Python
- Insert an Element in a Doubly Linked List in Python
- Print the Elements of a Doubly Linked List in Python
- Update an Element in a Doubly Linked List in Python
- Delete an Element From a Doubly Linked List in Python
- Complete Implementation of Doubly Linked List in Python
- Conclusion
What Is a Doubly Linked List?
A doubly linked list is a linked list in which the nodes are linked to each other using two references.
Each node in a doubly linked list consists of three attributes namely data
, next
, and previous
. You can visualize a node in a doubly linked list as follows.
Here,
- The
previous
attribute is used to refer to the previous node in the linked list. - The
data
attribute is used to store the data in the node. - The
next
attribute is used to refer to the next node in the linked list.
In a doubly linked list, there can be any number of nodes. All the nodes in the linked list are connected to each other using the previous and next attributes. You can visualize a doubly linked list having three nodes as follows.
In the above image, we have created a doubly linked list containing three nodes.
- The first node contains 5 in its
data
attribute and p1 and n1 as itsprevious
andnext
attribute respectively. - The second node contains 10 in its
data
attribute and p2 and n2 as itsprevious
andnext
attribute respectively. - The third node contains 15 in its
data
attribute and p3 and n3 as itsprevious
andnext
attribute respectively. - The
head
node does not contain any data and is used to refer to the first node in the linked list. - The
previous
attribute of the first node does not refer to any other node. It points toNone
. Similarly, thenext
attribute of the last node does not refer to any other node. It also points toNone
.
As we have a general idea of what a doubly linked list looks like, let us try to implement a doubly linked list in Python.
How to Create a Doubly Linked List in Python?
To create a doubly linked list in python, we will first create a node for a doubly linked list as shown below.
class Node:
def __init__(self, value):
self.previous = None
self.data = value
self.next = None
Here, the Node
class contains the attribute data
to store the data in the linked list. The previous
and next
attributes are used to connect the nodes in the doubly linked list in python.
After creating a node, we will create a DoublyLinkedList
class to implement a doubly linked list in python. The class will contain a head
attribute that is initialized to None
.
class DoublyLinkedList:
def __init__(self):
self.head = None
After creating the empty linked list, we can create a node and assign it to the head
attribute. To add more nodes to the linked list, you can manually assign the next
and the previous
attributes of the nodes.
Instead of manually assigning the nodes to the linked list, we can write a method to insert an element in a doubly linked list in python. We can also perform different operations like updating and deleting the elements from the doubly linked list in python. Let us discuss each operation one by one.
Check if a Doubly Linked List Is Empty in Python
To check if a doubly linked list is empty in python, we just have to check if the head
attribute of the linked list points to None
. If yes, we will say that the linked list is empty. Otherwise not.
For this operation, we will implement an isEmpty()
method. The isEmpty()
method, when invoked on a doubly linked list, will check whether the head
attribute of the linked list points to None
. If yes, it returns True
. Otherwise, it returns False
.
Following is the python implementation of the isEmpty()
method to check if a doubly linked list is empty or not.
def isEmpty(self):
if self.head is None:
return True
return False
Find the Length of a Doubly Linked List in Python
To find the length of the doubly linked list, we will follow the following steps.
- First, we will create a temporary variable
temp
and a counter variablecount
. - We will initialize the variable
temp
with thehead
of the doubly linked list. Also, we will initialize the variablecount
to 0. - Now we will traverse through the linked list using a while loop and the
temp
variable. - While traversal, we will first check if the current Node (
temp
) isNone
. If yes, we will get out of the loop. Otherwise, we will first increment thecount
by 1. After that, we will assign thetemp
variable to thenext
node of the current node.
After execution of the while loop, we will get the length of the doubly linked list in the variable count
.
Following is the implementation of the length()
method for doubly linked lists in python. When invoked on a doubly linked list, it calculates the length of the linked list and returns the value.
def length(self):
temp = self.head
count = 0
while temp is not None:
temp = temp.next
count += 1
return count
Search an Element in a Doubly Linked List in Python
To search an element in a doubly linked list in python, we will use the following algorithm.
- First, we will define a variable
temp
and initialize it to thehead
attribute of the linked list. - We will also define a variable
isFound
and initialize it toFalse
. This variable will be used to check if the given element is found in the doubly linked list or not. - After that, we will iterate through the nodes of the linked list using a while loop and the
temp
variable. - While iterating the nodes of the doubly linked list, we will perform the following operations.
- We will check if the current node is
None
. If yes, it means that we have reached the end of the linked list. Hence, we will move out of the while loop. - If the current node is not
None
, we will check if the data in the current node is equal to the value we are searching for. - If the element in the current node is equal to the element we are searching for, we will assign the value
True
to theisFound
variable. After that, we will move out of the while loop using the break statement. Otherwise, we will move to the next node in the linked list.
- We will check if the current node is
After execution of the while loop, if the isFound
variable has the value True
, the element is said to be found in the linked list. Otherwise not.
Following is the implementation of the search()
method. The search()
method, when invoked on a doubly linked list, takes an element as its input argument. After execution, it returns True if the element is found in the linked list. Otherwise, it returns False.
def search(self, value):
temp = self.head
isFound = False
while temp is not None:
if temp.data == value:
isFound = True
break
temp = temp.next
return isFound
Insert an Element in a Doubly Linked List in Python
While inserting an element in a doubly linked list in python, there can be four situations.
- We need to insert an element at the beginning of the linked list.
- We need to insert an element at a given position in the linked list.
- We need to insert an element after an element in the linked list.
- We need to insert an element at the end of the linked list.
Let us discuss each of the cases one by one.
Insert at the Beginning of a Doubly Linked List
To insert an element at the beginning of a doubly linked list in python, we will first check if the linked list is empty. You can check if the linked list is empty using the isEmpty()
method discussed in the previous section.
If the doubly linked list is empty, we will simply create a new node with the given data and assign it to the head
attribute of the linked list.
If the linked list is not empty, we will follow the following steps.
- First, we will create a new node with the given data that has to be inserted into the linked list.
- After that, we will assign the node referred by the
head
attribute of the linked list to thenext
attribute of the new node. - Then, we will assign the new node to the
previous
attribute of the node referred by thehead
attribute of the linked list. - Finally, we will assign the new node to the
head
attribute of the linked list.
After executing the above steps, the new element will be added to the doubly linked list at its beginning.
Following is the implementation of the insertAtBeginning()
method in python. The insertAtBeginning()
method, when invoked on a doubly-linked list, takes an element as its input argument and inserts it into the linked list at the beginning of the linked list.
def insertAtBeginning(self, value):
new_node = Node(value)
if self.isEmpty():
self.head = new_node
else:
new_node.next = self.head
self.head.previous = new_node
self.head = new_node
Insert at the End of the Doubly Linked List
To insert an element at the end of a doubly linked list in python, we will use the following algorithm.
- First, we will create a new node with the given element.
- After that, we will check if the doubly linked list is empty. If yes, we will use the
insertAtBeginning()
method to add the new element to the list. - Otherwise, we will define a variable
temp
and assign thehead
attribute to it. After that, we will move to the last node of the doubly linked list using a while loop. - In the while loop, we will check if the
next
attribute of the current node points toNone
. If yes, we have reached the last node of the list. Hence, we will move out of the loop. Otherwise, we will move to the next node. - After reaching the last node(
temp
), we will assign the new node to thenext
attribute of the last node. Then, we will assigntemp
to theprevious
attribute of the new node.
After execution of the above steps, the new element will be added to the end of the doubly linked list.
Following is the implementation of the insertAtEnd()
method. The insertAtEnd()
method, when invoked on a linked list, takes an element as its input argument and adds it to the end of the linked list.
def insertAtEnd(self, value):
new_node = Node(value)
if self.isEmpty():
self.insertAtBeginning(value)
else:
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = new_node
new_node.previous = temp
Insert After an Element of the Doubly Linked List
To insert a new element after another element in a doubly linked list in python, we will use the following steps.
First, we will define a variable temp
and initialize it to the head
attribute of the linked list. After that, we will iterate through the nodes of the linked list using a while loop and the temp
variable. While iterating the nodes of the doubly linked list, we will perform the following operations.
- We will check if the current node is
None
. If yes, it means that we have reached the end of the linked list. Hence, we will move out of the while loop. - If the current node is not
None
, we will check if thedata
in the current node is equal to the element after which we have to insert the new element. - If the element in the current node is equal to the element after which we have to insert the new element, we will move out of the while loop using the break statement. Otherwise, we will move to the next node in the linked list.
After execution of the while loop, there can be two situations.
- If the
temp
variable contains the valueNone
, it means that the element after which we have to insert the new value doesn’t exist in the linked list. In this case, we will print that the element cannot be inserted in the doubly linked list.
- If the
temp
variable is notNone
, we will insert the element in the linked list. For this, we will follow the following steps.- First, we will create a new node with the element that has to be inserted.
- We will assign the next node of the current node to the
next
attribute of the new node. After that, we will assign the current node to theprevious
attribute of the new node. - Then, we will assign the new node to the
previous
attribute of the next node of the current node. - Finally, we will assign the new node to the
next
attribute of the current node.
After executing the above steps, the new element will be inserted into the doubly linked list after the given value.
Following is the implementation of insertAfterElement()
method. The insertAfterElement()
method takes two values as its input argument. The first argument is the new value that is to be inserted into the linked list. The second argument is the element after which the new value has to be inserted.
After execution, the insertAfterElement()
method inserts the new element to the doubly linked list if the element after which the new value has to be inserted is present in the doubly linked list. Otherwise, it prints that the new element cannot be inserted into the linked list.
def insertAfterElement(self, value, element):
temp = self.head
while temp is not None:
if temp.data == element:
break
temp = temp.next
if temp is None:
print("{} is not present in the linked list. {} cannot be inserted into the list.".format(element, value))
else:
new_node = Node(value)
new_node.next = temp.next
new_node.previous = temp
temp.next.previous = new_node
temp.next = new_node
Insert at a Given Position in the Doubly Linked List
To insert an element at a given position N in a doubly linked list in python, we will follow the following steps.
If N==1, it means that the element has to be inserted at the first position. We will insert the element in the doubly linked list using the insertAtBeginning()
method. Otherwise, we will follow the following steps.
- First, we will define a variable
temp
and initialize it to thehead
attribute of the linked list. Then, we will initialize a variablecount
to 1. - After that, we will iterate through the nodes of the linked list using a while loop and the
temp
variable. - While iterating the nodes of the doubly linked list, we will perform the following operations.
- We will check if the current node is
None
. If yes, it means that we have reached the end of the linked list. Hence, we will move out of the while loop. - If the current node is not
None
, we will check if the variable count has a value equal to N-1. If yes, we will move out of the while loop using the break statement. Otherwise, we will move to the next node in the linked list.
- We will check if the current node is
After execution of the while loop, there can be two situations.
- If the
temp
variable contains the valueNone
, it means that there are less than N-1 elements in the linked list. In this case, we cannot insert the new node at the Nth position. Hence, we will print that the element cannot be inserted in the doubly linked list. - If the
temp
variable is notNone
, we will insert the element in the linked list. For this, we will have two choices. - First, we will check if the next node of the current node(
temp
) isNone
, if yes, we need to insert the new element at the end of the linked list. Therefore, we will use theinsertAtEnd()
method for the same. - If the next node of the current node is not
None
, we will use the following steps to insert the new element at the given position.- First, we will create a new node with the element that has to be inserted.
- We will assign the next node of the current node to the
next
attribute of the new node. - After that, we will assign the current node to the
previous
attribute of the new node. - Then, we will assign the new node to the
previous
attribute of the next node of the current node. - Finally, we will assign the new node to the
next
attribute of the current node.
After executing the above steps, the new element will be inserted into the doubly linked list at the given position.
Following is the implementation of insertAtPosition()
method. The insertAtPosition()
method takes two values as its input argument. The first argument is the new value that is to be inserted into the linked list. The second argument is the position at which the new value has to be inserted.
After execution, the insertAtPosition()
method inserts the new element at the desired position in the doubly linked list. Otherwise, it prints that the new element cannot be inserted into the linked list.
def insertAtPosition(self, value, position):
temp = self.head
count = 0
while temp is not None:
if count == position - 1:
break
count += 1
temp = temp.next
if position == 1:
self.insertAtBeginning(value)
elif temp is None:
print("There are less than {}-1 elements in the linked list. Cannot insert at {} position.".format(position,
position))
elif temp.next is None:
self.insertAtEnd(value)
else:
new_node = Node(value)
new_node.next = temp.next
new_node.previous = temp
temp.next.previous = new_node
temp.next = new_node
Print the Elements of a Doubly Linked List in Python
To print the elements of a doubly linked list in python, we will first define a variable temp
and assign the head
of the linked list to it. After that, we will use a while loop to iterate through the nodes of the linked list.
While iteration, we will first check if the current node in the doubly linked list is None
. If yes, we will move out of the while loop. Otherwise, we will print the data
attribute of the current node. Finally, we will move to the next node in the linked list using the next attribute of the nodes.
Following is the implementation of printLinkedList()
method. The printLinkedList()
method, when invoked on a doubly linked list, prints all the elements of the linked list.
def printLinkedList(self):
temp = self.head
while temp is not None:
print(temp.data)
temp = temp.next
Update an Element in a Doubly Linked List in Python
To update an element in a doubly linked list in python, we will first define a variable temp
and assign the head
of the linked list to it. We will also define a variable isUpdated
and initialize it to False
. After that, we will use a while loop to iterate through the nodes of the linked list.
While iteration, we will first check if the current node in the doubly linked list is None
. If yes, we will move out of the while loop. Otherwise, we will check if the data
attribute in the current node is equal to the value that needs to be replaced with a new value. If yes, we will update the data
attribute in the current Node and will update the value in isUpdated
to True
. Finally, we will move out of the while loop using break statement.
After executing the while loop, we will check if the isUpdated
is False. If yes, we will print that the value is not updated. Otherwise, we will print that the value is updated.
Following is the implementation of updateElement()
method. The updateElement()
method takes two values as its input argument. The first argument is the old value that is to be updated. The second argument is the new value.
After execution, the updateElement()
method updates the given element to the new value.
def updateElement(self, old_value, new_value):
temp = self.head
isUpdated = False
while temp is not None:
if temp.data == old_value:
temp.data = new_value
isUpdated = True
temp = temp.next
if isUpdated:
print("Value Updated in the linked list")
else:
print("Value not Updated in the linked list")
Update Element at a Given Position
To update an element at a given position N in a doubly linked list in python, we will use the following algorithm.
First, we will define a variable temp
and initialize it to the head
attribute of the linked list. Then, we will initialize a variable count to 1. After that, we will iterate through the nodes of the linked list using a while loop and the temp
variable.
While iterating the nodes of the doubly linked list, we will perform the following operations.
- We will check if the current node is
None
. If yes, it means that we have reached the end of the linked list. Hence, we will move out of the while loop. - If the current node is not
None
, we will check if the variable count has the value equal to N. If yes, we will move out of the while loop using the break statement. Otherwise, we will move to the next node in the linked list.
After execution of the while loop, there can be two situations.
- If the
temp
variable contains the valueNone
, it means that there are less than N elements in the linked list. In this case, we cannot update an element at the Nth position in the linked list. Hence, we will print that the element cannot be updated. - If the
temp
variable is notNone
, we will update the Nth element in the linked list by updating thedata
attribute of the current node.
Following is the implementation of updateAtPosition()
method. The updateAtPosition()
method takes two values as its input argument. The first argument is the new value that is to be updated in the linked list. The second argument is the position at which the new value has to be assigned.
After execution, the updateAtPosition()
method updates the element at the desired position in the doubly linked list.
def updateAtPosition(self, value, position):
temp = self.head
count = 0
while temp is not None:
if count == position:
break
count += 1
temp = temp.next
if temp is None:
print("Less than {} elements in the linked list. Cannot update.".format(position))
else:
temp.data = value
print("Value updated at position {}".format(position))
Delete an Element From a Doubly Linked List in Python
While deleting an element from a doubly linked list in python, there can be four cases.
- We need to delete an element from the start of the linked list.
- We need to delete an element from the end of the linked list.
- We need to delete a specific element.
- We need to delete an element from the given position in the linked list.
Let us discuss each of the cases one by one.
Delete From Beginning of the Doubly Linked List
To delete an element from the beginning of a doubly linked list, we will first check if the doubly linked list is empty. If yes, we will say that we cannot delete any element from the linked list.
Otherwise, we will check if there is only one element in the linked list i.e. the next
attribute of the head node points to None
or not. If the next attribute of the head
node is None, we will assign None
to the head
.
If there are more than one element in the linked list, we will move the head
of the linked list to the next
node of the current head
. After that, we will assign None
to the previous
attribute of the new head node.
After executing the above steps, the first node of the linked list will be deleted.
Following is the implementation of the deleteFromBeginning()
method. The deleteFromBeginning()
method, when invoked on a doubly linked list, deletes the first node of the linked list.
def deleteFromBeginning(self):
if self.head is None:
print("Linked List is empty. Cannot delete elements.")
elif self.head.next is None:
self.head = None
else:
self.head = self.head.next
self.head.previous = None
Delete the Last Element of the Doubly Linked List
To delete the last element of a doubly linked list in python, we will use the following steps.
- First, we will check if the doubly linked list is empty. If yes, we will say that we cannot delete any element from the linked list.
- Otherwise, we will check if the linked list has only one element i.e. the
next
attribute of thehead
node points toNone
or not. If thenext
attribute of the head node isNone
, we will assignNone
to thehead
. - If there are more than one elements in the linked list, we will create a variable
temp
and assign thehead
to the variable. After that, we will traverse the doubly linked list till we reach the last node of the list i.e. thenext
attribute of the current node becomesNone
. - After reaching the last node, we will assign
None
to thenext
attribute of the previous node of the current node. Subsequently, we will assignNone
to theprevious
attribute of the current node.
By executing the above steps, the last element of the doubly linked list will be deleted from the linked list.
Following is the implementation of deleteFromLast()
method. The deleteFromLast()
method, when invoked on a doubly linked list, deletes the last node of the linked list.
def deleteFromLast(self):
if self.isEmpty():
print("Linked List is empty. Cannot delete elements.")
elif self.head.next is None:
self.head = None
else:
temp = self.head
while temp.next is not None:
temp = temp.next
temp.previous.next = None
temp.previous = None
Delete a Given Element in the Doubly Linked List
To delete a given element from a doubly linked list in python, we will use the following steps.
- First, we will check if the doubly linked list is empty. If yes, we will say that we cannot delete any element from the linked list.
- Otherwise, we will check if the linked list has only one element i.e. the
next
attribute of the head node points toNone
or not. - If the
next
attribute of thehead
node is None, we will check if the element in the first node is the element to be deleted. If yes, we will assignNone
to thehead
. - If there are more than one element in the linked list, we will create a variable
temp
and assign thehead
to the variable. - After that, we will traverse the doubly linked list till last using the
temp
variable and a while loop. - While traversing the linked list, we will first check if the current node is
None
i.e. we have reached the end of the linked list. If yes, we will move out of the while loop. - If the current node is not
None
, we will check if the current node contains the element that needs to be deleted. If yes, we will move out of the while loop using a break statement.
After executing the while loop, there can be two situations.
- If the
temp
variable contains the valueNone
, it means that we have reached the end of the doubly linked list. In this case, we cannot delete an element from the linked list. Hence, we will print that the element cannot be deleted from the doubly linked list. - If the
temp
variable is not none, we will delete the element from the linked list. For this, we will have two choices.- First, we will check if the current node is the last node of the linked list i.e. the next node of the current node(
temp
) isNone
, if yes, we basically need to delete the last node of the linked list. Therefore, we will use thedeleteFromLast()
method for the same. - If the next node of the current node is not
None
, we will use the following steps to delete the given element. - We will assign the next node of the
temp
node to thenext
attribute of the previous node oftemp
. - Then, we will assign the previous node of the
temp
node to theprevious
attribute of the next node of temp. - Finally, we will assign
None
to theprevious
andnext
attributes of thetemp
node.
- First, we will check if the current node is the last node of the linked list i.e. the next node of the current node(
By executing the above steps, any given element, if present in the linked list, will be deleted from the linked list.
Following is the implementation of delete()
method. The delete()
method, when invoked on a doubly linked list, takes an element as an input argument and deletes its first occurrence from the linked list.
def delete(self, value):
if self.isEmpty():
print("Linked List is empty. Cannot delete elements.")
elif self.head.next is None:
if self.head.data == value:
self.head = None
else:
temp = self.head
while temp is not None:
if temp.data == value:
break
temp = temp.next
if temp is None:
print("Element not present in linked list. Cannot delete element.")
elif temp.next is None:
self.deleteFromLast()
else:
temp.next = temp.previous.next
temp.next.previous = temp.previous
temp.next = None
temp.previous = None
Delete From a Given Position in the Doubly Linked List
To delete an element from a given position N in a doubly linked list in python, we will use the following algorithm.
First, we will check if the linked list is empty. If yes, we will say that we cannot delete any element.
After that, we will check If N==1, which means that we need to delete the element from the first position. If yes, we will delete the first element using the deleteFromBeginning()
method.
Otherwise, we will follow the following steps.
- First, we will define a variable
temp
and initialize it to thehead
attribute of the linked list. Then, we will initialize a variablecount
to 1. - After that, we will iterate through the nodes of the linked list using a while loop and the
temp
variable. - While iterating the nodes of the doubly linked list, we will perform the following operations.
- We will check if the current node is
None
. If yes, it means that we have reached the end of the linked list. Hence, we will move out of the while loop. - If the current node is not
None
, we will check if the variablecount
has the value equal to N. If yes, we will move out of the while loop using the break statement. Otherwise, we will move to the next node in the linked list.
- We will check if the current node is
After execution of the while loop, there can be two situations.
- If the
temp
variable contains the valueNone
, it means that there are less than N elements in the linked list. In this case, we cannot delete an element from Nth position in the linked list. Hence, we will print that the element cannot be deleted from the doubly linked list. - If the
temp
variable is not none, we will delete the Nth element from the linked list. For this, we will have two choices.- First, we will check if the next node of the current node(
temp
) is None. If yes, the Nth element is the last element of the linked list. Therefore, we will use thedeleteFromEnd()
method to delete the element. - If the Nth element isn’t the last element of the doubly linked list, we will perform the following operations to delete the Nth element.
- We will assign the next node of the
temp
(the current node) to thenext
attribute of the previous node of temp. - Then, we will assign the previous node of the
temp
node to theprevious
attribute of the next node oftemp
. - Finally, we will assign
None
to theprevious
andnext
attributes of thetemp
node.
- First, we will check if the next node of the current node(
By executing the above steps, any given element, if present in the linked list, will be deleted from the linked list.
Following is the implementation of deleteFromPosition()
method. The deleteFromPosition()
method, when invoked on a doubly linked list, takes the position from which the element has to be deleted as its input argument. After execution, it deletes the element from the specified position in the doubly linked list.
def deleteFromPosition(self, position):
if self.isEmpty():
print("Linked List is empty. Cannot delete elements.")
elif position == 1:
self.deleteFromBeginning()
else:
temp = self.head
count = 1
while temp is not None:
if count == position:
break
temp = temp.next
if temp is None:
print("There are less than {} elements in linked list. Cannot delete element.".format(position))
elif temp.next is None:
self.deleteFromLast()
temp.previous.next = temp.next
temp.next.previous = temp.previous
temp.next = None
temp.previous = None
Complete Implementation of Doubly Linked List in Python
Now that we have discussed all the methods to implement a doubly linked list in python, let us execute the program to observe the implementation.
class Node:
def __init__(self, value):
self.previous = None
self.data = value
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def isEmpty(self):
if self.head is None:
return True
return False
def length(self):
temp = self.head
count = 0
while temp is not None:
temp = temp.next
count += 1
return count
def search(self, value):
temp = self.head
isFound = False
while temp is not None:
if temp.data == value:
isFound = True
break
temp = temp.next
return isFound
def insertAtBeginning(self, value):
new_node = Node(value)
if self.isEmpty():
self.head = new_node
else:
new_node.next = self.head
self.head.previous = new_node
self.head = new_node
def insertAtEnd(self, value):
new_node = Node(value)
if self.isEmpty():
self.insertAtBeginning(value)
else:
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = new_node
new_node.previous = temp
def insertAfterElement(self, value, element):
temp = self.head
while temp is not None:
if temp.data == element:
break
temp = temp.next
if temp is None:
print("{} is not present in the linked list. {} cannot be inserted into the list.".format(element, value))
else:
new_node = Node(value)
new_node.next = temp.next
new_node.previous = temp
temp.next.previous = new_node
temp.next = new_node
def insertAtPosition(self, value, position):
temp = self.head
count = 0
while temp is not None:
if count == position - 1:
break
count += 1
temp = temp.next
if position == 1:
self.insertAtBeginning(value)
elif temp is None:
print("There are less than {}-1 elements in the linked list. Cannot insert at {} position.".format(position,
position))
elif temp.next is None:
self.insertAtEnd(value)
else:
new_node = Node(value)
new_node.next = temp.next
new_node.previous = temp
temp.next.previous = new_node
temp.next = new_node
def printLinkedList(self):
temp = self.head
while temp is not None:
print(temp.data, sep=",")
temp = temp.next
def updateElement(self, old_value, new_value):
temp = self.head
isUpdated = False
while temp is not None:
if temp.data == old_value:
temp.data = new_value
isUpdated = True
temp = temp.next
if isUpdated:
print("Value Updated in the linked list")
else:
print("Value not Updated in the linked list")
def updateAtPosition(self, value, position):
temp = self.head
count = 0
while temp is not None:
if count == position:
break
count += 1
temp = temp.next
if temp is None:
print("Less than {} elements in the linked list. Cannot update.".format(position))
else:
temp.data = value
print("Value updated at position {}".format(position))
def deleteFromBeginning(self):
if self.isEmpty():
print("Linked List is empty. Cannot delete elements.")
elif self.head.next is None:
self.head = None
else:
self.head = self.head.next
self.head.previous = None
def deleteFromLast(self):
if self.isEmpty():
print("Linked List is empty. Cannot delete elements.")
elif self.head.next is None:
self.head = None
else:
temp = self.head
while temp.next is not None:
temp = temp.next
temp.previous.next = None
temp.previous = None
def delete(self, value):
if self.isEmpty():
print("Linked List is empty. Cannot delete elements.")
elif self.head.next is None:
if self.head.data == value:
self.head = None
else:
temp = self.head
while temp is not None:
if temp.data == value:
break
temp = temp.next
if temp is None:
print("Element not present in linked list. Cannot delete element.")
elif temp.next is None:
self.deleteFromLast()
else:
temp.next = temp.previous.next
temp.next.previous = temp.previous
temp.next = None
temp.previous = None
def deleteFromPosition(self, position):
if self.isEmpty():
print("Linked List is empty. Cannot delete elements.")
elif position == 1:
self.deleteFromBeginning()
else:
temp = self.head
count = 1
while temp is not None:
if count == position:
break
temp = temp.next
if temp is None:
print("There are less than {} elements in linked list. Cannot delete element.".format(position))
elif temp.next is None:
self.deleteFromLast()
temp.previous.next = temp.next
temp.next.previous = temp.previous
temp.next = None
temp.previous = None
x = DoublyLinkedList()
print(x.isEmpty())
x.insertAtBeginning(5)
x.printLinkedList()
x.insertAtEnd(10)
x.printLinkedList()
x.deleteFromLast()
x.printLinkedList()
x.insertAtEnd(25)
x.printLinkedList()
x.deleteFromLast()
x.deleteFromBeginning()
x.insertAtEnd(100)
x.printLinkedList()
Output:
True
5
5
10
5
5
25
100
Conclusion
In this article, we have discussed the implementation of doubly linked list in python. I hope this article helps you learn all the concepts of doubly linked lists in python. If you find any bugs or improvements in the implementation, do let us know in the comments.
To learn more about python programming, you can read this article on how to find the index of max value in a list in python. You might also like this article on how to sort list of objects in python.
Stay tuned for more informative articles.
Happy Learning!
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.