哈希表中的下一个哈希冲突键

时间:2016-12-18 05:58:08

标签: 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);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

tempHash = current;

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

您有两个选择

<强>第一

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

<强>第二

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

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