I was reading the book Introduction To Algorithms and I came across this:
We can delete an element in O(1) time if the lists are doubly linked. (Note that CHAINED-HASH-DELETE takes as input an element x and not its key k, so that we don’t have to search for x first. If the hash table supports deletion, then its linked lists should be doubly linked so that we can delete an item quickly. If the lists were only singly linked, then to delete element x, we would first have to find x in the list T[h(x.key)] so that we could update the next attribute of x’s predecessor. With singly linked lists, both deletion and searching would have the same asymptotic running times.)
How can we delete an element in O(1) time if the lists are double linked? First we will need to find the element and then we can delete it in O(1). But to find it we need O(length of the list) time. Maybe it's faster deleting in a doubly linked list (because we can search from the both ends of the list at the same time, but that is only constant improvement), but I don't see how it can be done in O(1) time.
Thank you in advance.
O(n)
. The actual deletion isO(1)
in a doubly-linked list, or in a singly-linked list if you've kept track of the predecessor during the find stage (or if you play tricks like moving the next node data into the current node and deleting the next node instead). However, if you haven't tracked your predecessor node, and you don't move nodes, deletion in the singly-linked list isO(n)
– twalberg