Hi, I'm running in a little trouble here. I have a hash functions which hashes a string into a hash table that is linked via linked list. It seems to produce duplicates in my node. Here are pieces of the code :
I have a fixed length record of 20 chars read from a file, I placed 21 because of the "\n". After running a strlen to count, my output is as follows :
Code:
Output:
Length : 0 0
Length : 21 0
Length : 42 21
Length : 42 21
Seems that it manage to sneak another record into my first variable. I can't figure out what's wrong.
Code:
typedef struct Bucket
{
/* Extra node for chaining (Not relevant) */
OverflowBucket* head;
char record1[21];
char record2[21];
struct Bucket* next;
}Bucket;
/* Hash Table */
typedef struct Hashtable
{
Bucket* head;
}HashTable;
/* This is something to simplify you guys to generate the table of 0,1,2 string keys*/
HashTable* generateTable(HashTable* table)
{
int counter = 4;
Bucket *bucket, *currBucket;
while(counter != 0)
{
bucket = malloc(sizeof(Bucket));
if(bucket == NULL)
{
fprintf(stderr,"Malloc bucket failed\n");
exit(1);
}
bucket->next = NULL;
if(table->head == NULL)
{
table->head = bucket;
currBucket = bucket;
}
else
{
currBucket->next = bucket;
}
counter--;
}
return table;
}
int hash(char* buffer)
{
int h = 0, a = 127;
for(;*buffer != '\0'; buffer++)
h = (a*h + *buffer) % 3;
return h;
}
void hashToTable(char* buffer,HashTable* table)
{
int key,count;
Bucket *currBucket;
currBucket = table->head;
key = hash(buffer);
count = key;
/* if string key is 0 */
if(key == 0)
{
if(strlen(currBucket->record1) == 0)
strcpy(currBucket->record1,buffer);
else if(strlen(currBucket->record2) == 0)
strcpy(currBucket->record2,buffer);
}
else
{
/* Get corresponding node to the string key */
while(currBucket->next != NULL)
{
if(count != 0)
{
count--;
currBucket = currBucket->next;
}
else
{
if(strlen(currBucket->record1) == 0)
strcpy(currBucket->record1,buffer);
else if(strlen(currBucket->record2) == 0)
strcpy(currBucket->record2,buffer);
}
}
}
}