DLL
DLL
# If curr becomes None, the given key is not found in the linked list
if curr is None:
return head
# Update the prev of new node's next with the new node
if new_node.next is not None:
new_node.next.prev = new_node
return head
# If the linked list is empty, set the new node as the head
if head is None:
head = new_node
else:
curr = head
while curr.next is not None:
curr = curr.next
return head
To delete a node at the beginning in doubly linked list, we can use the
following steps:
Check if the list is empty, there is nothing to delete, return.
Store the head pointer in a variable, say temp.
Update the head of linked list to the node next to the current
head, head = head->next.
If the new head is not NULL, update the previous pointer of new head
to NULL, head->prev = NULL.
def del_head(head):
To delete a node after a specific node in a doubly linked list, we can use
the following steps:
Initialize a variable , say curr points to the node with the key value in
the linked list.
if found , check if curr->next is not NULL.
o If it’s NULL then there is no node to delete , return.
o else , set a pointer nodeDelete to curr->next, which is the
node to be deleted.
o Update curr->next to point to nodeDelete->next.
o If nodeDelete->next is not NULL, update
the previous pointer of nodeDelete->next to curr.
Delete nodeDelete to free memory.
# Node to be deleted
node_delete = curr.next
return head
To delete a node at the end in doubly linked list, we can use the following
steps:
Check if the doubly linked list is empty. If it is empty, then there is
nothing to delete.
If the list is not empty, then move to the last node of the doubly linked
list, say curr.
Update the second-to-last node’s next pointer to
NULL, curr->prev->next = NULL.
Free the memory allocated for the node that was deleted.
def del_last(head):
if head is None:
return None
if head.next is None:
return None
TRAVERSAL
Algorithm
Recursively traverse the doubly linked list until it reaches the last node.
While backtracking, reverse the links between the nodes. To reverse
the links:
o Change the next pointer of the current node to point to
its previous node.
o Change the prev pointer of the current node to point to
its next node.
Adjust the head of the doubly linked list to point to the last node.
def reverse(curr):
def print_list(node):
while node is not None:
print(node.data, end=" ")
node = node.next
print()
def reverse(self):
prev = None
current = self.head
while(current is not None):
next = current.next
current.next = prev
prev = current
current = next
self.head = prev