c - 将冲突键哈希到哈希表中的下一个

标签 c algorithm data-structures hash hashtable

我在链接冲突的键时遇到问题,最新的键将覆盖链接到表的前一个键。我已经对碰撞进行了硬编码,以查看碰撞的键是否正确保存在链表中,但未正确保存。 这是代码的相关部分。

typedef struct student 
{
    char name[10];
    char sex[4];
    char number[12];
    char mail[50];
    bool filled;
    struct student *next;
}ST;

void Readfromfile(ST *hashTable)//Read data from txt file and build hash table
{
    FILE *ft;
    ft = fopen("info.txt", "r");
    if(!ft)
    {
        printf("FAILED TO OPEN FILE\n");
        return;
    }
    char *buffer = malloc(sizeof(char)*43);
    char cp_name[10], cp_sex[4], cp_num[12], cp_mail[50];
    int st_index =0, i;
    while((fgets(buffer, sizeof(buffer)*50, ft)) != NULL)
    {
        if(strlen(buffer) != 0)
            sscanf(buffer, "%s %s %s %s", cp_name, cp_sex, cp_num, cp_mail);
        printf("READ: %s", buffer);
        int hash_value = Hashfun(cp_num);
        ST *current = malloc(sizeof(ST));
        strcpy(current->name, cp_name);
        strcpy(current->sex, cp_sex);
        strcpy(current->number, cp_num);
        strcpy(current->mail, cp_mail);
        current->filled = true;
        current->next = NULL;
        ST *tempHash = &hashTable[hash_value];
        if(tempHash->filled == true)
        {
            printf("THERE IS A COLLISION at %d SAVING AT NEXT \n\n\n",hash_value);
            while(tempHash!= NULL)
            {
                printf("I AM PROBLEM HEREEEEEEEEEEEEEEEEEEEEEEE\n");
                printf("PASSING BY: %s %s %s %s at %d\n",tempHash->name,tempHash->sex,
                       tempHash->number,tempHash->mail, hash_value);
                tempHash = tempHash->next;
            }
            tempHash = current;
            printf("HASHED NEXT: %s %s %s %s at %d\n",tempHash->name,tempHash->sex, tempHash->number,
                   tempHash->mail, hash_value);
        }
        else
        {
            strcpy(tempHash->name, cp_name);
            strcpy(tempHash->sex, cp_sex);
            strcpy(tempHash->mail, cp_mail);
            strcpy(tempHash->number, cp_num);
            tempHash->filled = true;
            tempHash->next = NULL;
            printf("HASHED: %s %s %s %s at %d\n",tempHash->name,tempHash->sex,        tempHash->number,
                   tempHash->mail, hash_value);
        }
    }
}

最佳答案

tempHash = current;

tempHash 在while(tempHash!= NULL) 循环后指向 null。

你有两个选择

首先

while(tempHash->next!= NULL) {
  tempHash = tempHash->next;
}
tempHash->next = current;

第二

不是将 current 元素添加到末尾,而是直接将其添加为链接列表的第一个元素。

if(tempHash->filled == true)
{
   current->next = tempHash;
   hashTable[hash_value] = current;
}

关于c - 将冲突键哈希到哈希表中的下一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41205894/

相关文章:

c - 为什么这段 Prolog+C 代码失败了?

c - 从另一个线程访问主线程的局部变量

algorithm - 为什么广度优先搜索有两个列出的时间复杂度?

c - 致命信号 11 退出状态

algorithm - 算法中的抽象数据类型

C++11 复杂<浮点>* 到 C 浮点复杂*

c - 使用C使用TCP连接到端口

algorithm - (批处理)SOM(自组织映射,又名 "Kohonen Map")的收敛标准?

c++ - 集合论的取组合问题

C# DataTable,通过行/列索引获取值