For a piece of coursework I am going to use hash tables. I have decdied to try and learn them by just writing a small program to enter data into a hash table and then print out the last thing that was entered. But it is the entry into the hash that is most important. Here is the code I have written:
#include <stdio.h>
#include <stdlib.h>
/*defien structure and types*/
typedef struct list
{
char word[50];
struct list *next;
}LIST;
typedef LIST *P_LIST;
P_LIST hash_table[5];
P_LIST insert(char string[],P_LIST head);
int hash(char word[]);
int main ()
{
int h, i;
P_LIST output;
char keyword[50], input[50];
for (i=0; i < 7; i++)
{
printf ("Enter word to put in hash table: ");
scanf ("%s", &keyword);
h = hash(input);
output = hash_table[h];
output = insert(input,output);
}
printf("%s", output -> word);
}
/*Finds a key value for the word*/
int hash(char word[])
{
{
int i = 0;
unsigned sum = 1;
unsigned key;
while (word[i] != '\0')
{
sum = sum * word[i];
i++;
}
key = sum % 5;
return key;
}
}
/*Inserts into the list pointed to by the hed parameter*/
P_LIST insert(char string[],P_LIST head)
{
P_LIST node;
node = malloc(sizeof(LIST));
node -> next = head;
head = node;
strcpy (node -> word, string);
return head;
}
Is this the right way to enter stuff into a hash table or am I doing it wrong?