Deleting a node in a doubly linked list is very similar to deleting a node in a singly linked list. However, there is a little extra work required to maintain the links of both the previous and next nodes.
Deletion in a doubly linked list means removing a node from the list while keeping the links between the remaining nodes intact.
It involves adjusting the next pointer of the previous node and the prev pointer of the next node.
After updating the links, the deleted nodeβs memory is freed.
Deletion at the Beginning in Doubly Linked List
The idea is to update the head of the doubly linked list to the node next to head node and if the new head is not NULL, then set the previous pointer of new head to NULL.
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.
If it's NULL then there is no node to delete , return.
else , set a pointer nodeDelete to curr->next, which is the node to be deleted.
Update curr->next to point to nodeDelete->next.
If nodeDelete->next is not NULL, update the previous pointer of nodeDelete->next to curr.
Delete nodeDelete to free memory.
Output
1 2 4
Time Complexity: O(n), where n is the number of nodes in doubly linked list. Auxiliary Space: O(1)
Deletion before a given node in Doubly Linked List
Deletion before a given node in a doubly linked list means removing the node that comes just before a specific node. We find the target node, move to its previous node, and adjust the links so the node before it is skipped.
To delete a node at a specific position in doubly linked list, we can use the following steps:
Traverse to the node at the specified position, say curr.
If the position is valid, adjust the pointers to skip the node to be deleted.
If curr is not the head of the linked list, update the next pointer of the node before curr to point to the node after curr, curr->prev->next = curr->next.
If curr is not the last node of the linked list, update the previous pointer of the node after curr to the node before curr, curr->next->prev = curr->prev.
Free the memory allocated for the deleted node.
Output
1 3
Time Complexity: O(n), where n is the number of nodes in the doubly linked list. Auxiliary Space: O(1)
Deletion at the End in Doubly Linked List
Deletion at the end in a doubly linked list means removing the last node of the list. We move to the last node, change the next pointer of its previous node to NULL, and free the memory of the last node.