考慮下面的代碼片段:搜索一個完整的哈希表
#include<stdio.h>
#include<conio.h>
#define TABLESIZE 100
sturct record{
int k;
int r;
}table[TABLESIZE];
int tcount=0;
int search_and_insert(int key,int rec){
int i;
i=h(key);
while(table[i].k!=key && table[i].k!=NULL)
i=rh(i);
if(table[i].key==NULL){
table[i].k=key;
table[i].r=rec;
tcount++;
}
return i;
}
int h(int key){
return key%1000;
}
int rh(int hkey){
int k;
if(hkey==99)
return 0;
return ((hkey+1)%1000);
}
的while
循環可能無限循環,如果表已經滿了,要解決這個問題,我可以 引入if
聲明是這樣的:
if(tcount<TABLESIZE){
while(table[i].k!=key && table[i].k!=NULL)
i=rh(i);/*Rehash*/
if(table[i].key==NULL){
table[i].k=key;
table[i].r=rec;
tcount++;
}
}
但根據我這引起了另一個問題,即我將無法搜索已經存在於表中的記錄,當表已滿或搜索將提供一個錯誤的結果。
可以解決這個問題嗎?
「int」永遠不能是「NULL」。您需要爲每個存儲桶分配一個標記以指示它是否正在使用。 – 2013-03-26 13:09:06