Why deletion of elements of hash table using doubly-linked list is O(1)?

前端 未结 8 1360
野的像风
野的像风 2020-12-23 10:20

On CLRS\'s textbook \"Introduction to Algorithm\", there\'s such paragraph on pg. 258.

We can delete an element in O(1) time if the lists are doubly linked. (Note th

8条回答
  •  盖世英雄少女心
    2020-12-23 11:00

    Find(x) is, in general, O(1) for a chained hash table -- it is immaterial whether or not you use singly linked lists or doubly linked lists. They are identical in performance.

    If, after having run Find(x), you decide that you'd like to delete the object returned, you will find that, internally, a hash table might have to search for your object again. It's still usually going to be O(1) and not a big deal, but you find that you delete an awful lot, you can do a little better. Instead of returning a user's element directly, return a pointer to the underlying hash node. You can then take advantage of some internal structures. So if in this case, you chose a doubly linked list as the way to express your chaining, then during the delete process, there is no need to recompute the hash and search the collection again -- you can omit this step. You have enough information to perform a delete right from where you are sitting. Additional care must be taken if the node you are submitting is the head node, so an integer might be used to mark the location of your node in the original array if it is the head of a linked list.

    The trade-off is the guaranteed space taken by the extra pointer versus a possible faster delete (and slightly more complicated code). With modern desktops, space is usually very cheap, so this might be a reasonable trade-off.

提交回复
热议问题