4
有人可以給我看一個合併鏈式散列表的刪除算法的例子嗎?合併散列刪除算法
我插入算法是這樣的:
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
假設中的插槽表中的號碼是13。散列函數返回鍵%13。
Keys | 5 | 18 | 16 | 15 | 13 | 31 | 26 |
Hash(key)| 5 | 5 | 3 | 2 | 0 | 5 | 0 |
順序將它們插入後,我的表將是這個樣子:
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|
其中-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
我不認爲這是在做正確的方式,但它似乎是工作。無論如何,我希望將來能夠幫助別人。
讓我們看看插入後得到的表格。我想刪除鍵18.它的PP是5.如果我做下一個[PP] =下一個[P],這意味着從索引5我可以跳轉到索引1.好吧,那很好。但是在索引1中,我有一個散列值爲0的密鑰。如果我想搜索那個密鑰,我找不到它。因爲D [0]現在是空閒的,所以它必須移動到索引0處的正確位置。如果我在嘗試搜索關鍵字13(hash(13)= 0)時不移動這些項目,我將首先檢查D [hash(13)],這將是NIL,我會認爲該項目不存在。但該項目確實存在於索引1。 – Bogdan 2011-07-18 09:13:10