我正在尝试为 C 中的哈希表实现冲突解决的线性探测。我正在使用 RRN(记录相对编号)从文件中插入和检索信息,以定位将插入/检索每个寄存器的索引。最初,我将所有索引值设置为“_”作为将它们标记为空的一种方式。到目前为止,一切都很好。我遇到的问题是当我实际尝试实施碰撞解决方案时。该程序似乎正在覆盖那里的记录,而不是寻找下一个可用位置。此外,当我有目的地查找不存在键(名称)的记录时,程序会卡住。
每当 fd=0 时(换句话说,当它到达文件末尾时),我都会将指针设置回文件的开头,但有些东西告诉我这可能是问题所在。大家可以看看吗?提前致谢:
//Simplified data struct that will be used
struct client{
char last_name[15];
char maiden_name[15];
char name[15];
}client
//Hash function
int Hash(char nm[15]){
int key, sum = 0, i;
//Sums the ASCII values of each letter in the client's name
for (i=0;nm[i]!='\0';i++){
sum=sum+nm[i];
}
key=sum%10; // Divides the sum by 10 and saves the modulus value in key variable
return key;
}
为了清楚起见,我省略了一些代码,但这是我实现 while 循环以验证寄存器是否为空的地方:
key= Hash(buff.name); // Uses Hash function to get key (index) value of where record will be stored
beginning=key;
lseek(fd, sizeof(client) * key, SEEK_SET); // Moves pointer to insert location
read(fd, &read_buf, sizeof (client)); // Reads the record contents in memory
while((strcmp("_",read.name)) != 0){ // While record is not empty...
++key; //Increase the key value
lseek(fd, sizeof (client) * key,SEEK_SET); // Change pointer to new location
read(fd, &read_buf, sizeof (client)); // Read contents into memory again
if (fd==0){ //If file descriptor reaches end of file, set key back to the beginning
key=0;
}
if (key== beginning){ // If key reaches the origin location of the search, print out error and exit
printf("There are no more spaces in the file!");
break;
}
}
write(fd, &buff, sizeof client);
printf("The record has been inserted successfully!\n");