Reputation: 37
I have a problem in linking the collided keys, the latest key will override the previous key that was linked to the table. I have hard coded for a collision to see if the keys that collide are saved in the linked list correctly, but its not saved correctly. Here is the involved part of the code.
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);
}
}
}
Upvotes: 1
Views: 69
Reputation: 1497
tempHash = current;
tempHash points to null afterwhile(tempHash!= NULL)
loop.
You have two options
First
while(tempHash->next!= NULL) {
tempHash = tempHash->next;
}
tempHash->next = current;
Second
Instead of adding the current
element to the end, directly add it as the first element of your linked list.
if(tempHash->filled == true)
{
current->next = tempHash;
hashTable[hash_value] = current;
}
Upvotes: 2