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

前端 未结 8 1361
野的像风
野的像风 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 10:54

    The problem presented here is : consider you have are looking at a particular element of a hashtable. How costly is it to delete it?

    Suppose you have a simple linked list :

    v ----> w ----> x ----> y ----> z
                    |
                you're here
    

    Now if you remove x, you need to connect w to y to keep your list linked. You need to access w and tell it to point to y (you want to have w ----> y). But you can't access w from x because it's simply linked! Thus you have to go through all your list to find w in O(n) operations, and then tell it to link to y. That's bad.

    Then, suppose you're doubly-linked :

    v <---> w <---> x <---> y <---> z
                    |
                you're here
    

    Cool, you can access w and y from here, so you can connect the two (w <---> y) in O(1) operation!

提交回复
热议问题