合并散列删除算法

Bog*_*dan 6 algorithm hash pseudocode

有人可以向我展示一个合并链式哈希表的删除算法示例吗?

我的插入算法是这样的:

Insert (key) 
    int p = hash(key)
    if d[p] = NIL then
        d[p] = key
        next[p] = NIL
    else
        while next[p] != NIL 
            p = next[p]
        endwhile
        td[firstEmpty] = key
        next[p] = firstEmpty
        next[firstEmpty] = NIL
    endif
    UpdateFirstEmpty(); //sets firstEmpty to first empty slot with lowest index
endInsert
Run Code Online (Sandbox Code Playgroud)

假设表中的槽数为 13。散列函数返回Key%13

    Keys | 5 | 18 | 16 | 15 | 13 | 31 | 26 |      
Hash(key)| 5 |  5 |  3 |  2 |  0 |  5 |  0 |
Run Code Online (Sandbox Code Playgroud)

按此顺序插入它们后,我的表将如下所示:

index|  0|  1|  2|  3|  4|  5|  6|  7|  8|  9| 10| 11| 12|
    d| 18| 13| 15| 16| 31|  5| 26| -1| -1| -1| -1| -1| -1|
 next|  1|  4| -1| -1|  6|  0| -1| -1| -1| -1| -1| -1| -1|
Run Code Online (Sandbox Code Playgroud)

where -1 = NIL

如果有人可以向我解释在移除钥匙时我应该尝试做什么而不破坏链条,即使是用语言表达,我也会非常感激。

谢谢


编辑 -:我想我终于明白了..我使用的技术与从开放地址哈希表中删除项目时使用的技术相同。

事情是这样的:

Search for key position and it's predecessor pp
    if key is found at position p
        if pp != NIL then 
             next[pp] = NIL  
        d[p] = NIL           //deletes the key
        p = next[p]          //move position to next value in the chain
        UpdateFirstEmpty()
        while d[p] != NIL do
            temp = d[p]      //save value
            d[p] = NIL       //delete value 
            p = next[p]      //move position to next value in chain
            UpdateFirstEmpty()
            Insert(temp)     //insert the value in the list again
        endwhile
   endif
endalg

index|  0|  1|  2|  3|  4|  5|  6|  7|  8|  9| 10| 11| 12|
    d| 18| 13| 15| 16| 31|  5| 26| -1| -1| -1| -1| -1| -1|
 next|  1|  4| -1| -1|  6|  0| -1| -1| -1| -1| -1| -1| -1|
firstFree: 7

delete 18

index|  0|  1|  2|  3|  4|  5|  6|  7|  8|  9| 10| 11| 12|
    d| 13| 31| 15| 16| 26|  5| -1| -1| -1| -1| -1| -1| -1|
 next|  4| -1| -1| -1| -1|  1| -1| -1| -1| -1| -1| -1| -1|
firstFree: 6

delete 13

index|  0|  1|  2|  3|  4|  5|  6|  7|  8|  9| 10| 11| 12|
    d| 26| 31| 15| 16| -1|  5| -1| -1| -1| -1| -1| -1| -1|
 next| -1| -1| -1| -1| -1|  1| -1| -1| -1| -1| -1| -1| -1|
firstFree: 4

delete 26

index|  0|  1|  2|  3|  4|  5|  6|  7|  8|  9| 10| 11| 12|
    d| -1| 31| 15| 16| -1|  5| -1| -1| -1| -1| -1| -1| -1|
 next| -1| -1| -1| -1| -1|  1| -1| -1| -1| -1| -1| -1| -1|
firstFree: 0
Run Code Online (Sandbox Code Playgroud)

我认为这不是正确的做法,但它似乎奏效了。无论如何,我希望将来会帮助某人。

moh*_*it 0

我们可以做的一件事是简化删除操作:假设 PP 是节点 P(待删除)的父节点。由于我们知道合并哈希是线性探测和链接的结合。因此,我们可以简单地将 NULL 放入 data 和 P 的下一部分中,然后将 Next[PP] 填充到 Next[p],而不是将 P 之后的所有链元素向上吸。因此,下次当哈希函数将某个键映射到该位置时,它可以简单地将其放在那里。算法如下所示: 删除:

Next[PP]=Next[P];  //as simple as deletion in link list without deleting node here
D[P]=NULL;
Next[P]=NULL;
Run Code Online (Sandbox Code Playgroud)

我们就完成了。现在,线性探测(在发生冲突的情况下)将遵循每个冲突节点中的下一个指针,而不是紧随其后的下一个空闲位置以将其合并到链中。