![]() |
VOOZH | about |
To delete a node from a linked list we need to break the link between that node and the one pointing to that node. Assume node X needs to be deleted and node Y is the one pointing to X. So, we will need to break the link between X and Y and Y will point to the node which was being pointed by X.
There can be three types of deletions:
All the cases do not take O(1) time. Check the below section to find the time complexities of different operations.
Deletion from the beginning:
Deletion from the end:
There are 3 cases when deleting in a singly linked list is O(1), because we do not have to traverse the list.
When we have the pointer pointing to the node which needs to be deleted, let's call it prev. So, we have to do,
Since curr is the node that is deleted from the singly linked list.
When we have to delete the first/start/head node, let's call it head. So, we have to do,
Hence head is pointing to the next node.
When we have to delete the last/end/tail node, let's call it tail. So, we have to do,
This is only possible if we maintain an extra pointer except the head i.e., tail for referencing the last node of the linked list. But we can do this only once because after doing this we lose the reference of the last node and there is no way to find the reference of the new last node in O(1) in a singly linked list. In a doubly linked list, it is possible as it contains the previous pointer.
Below is the implementation of different deletion operations in a singly linked list:
Original list: 10 20 30 40 List after deleting the starting node: 20 30 40 List after deleting the ending node: 20 30 List after deleting the given node: 20