ok i need to design a hash tables that uses direct chaining as a collision resolution method.
my program needs to read in a .txt file and insert words into a hash table. i know who to make it read in and stuff and i got the basic hash function. I am stuck on how to actually write a function that installs words into a table and if the word is already there it uses linked list to put another one in. as far as i understand install function needs to use lookup function to check if the word is already there. is that correct? here is what i got so far:
Code:
typedef struct nlist { char k[40]; struct nlist *next; } ;

#define HASHSIZE 101

static struct nlist *hashtab[HASHSIZE];

unsigned hash (char *s)
{
	unsigned hashval;
	
	for (hashval = 0; *s != '\0'; s++)
		hashval = *s + 31 * hashval;
	return hashval % HASHSIZE;
}
this is the a basic hash func i am testing. here is the lookup function i got from a book and hoped to modify to match my requirements:
Code:
struct nlist *lookup (char *s)
{	
	struct nlist *np;
	
	for (np = hashtab[hash(s)]; np != NULL; np = np -> next)
		if (strcmp(s, np -> k) == 0)
			return np;
	return NULL;
}
and this is the install func, but this one instead of adding another word to the list, it replaces it which is something i don't want it to do:
Code:
struct nlist *install (char *name)
{
	struct nlist *np;
	unsigned hashval;
	
	if ((np = lookup (name)) == NULL){
		np = (struct nlist *) malloc (sizeof (*np));
		if (np == NULL || (np -> name = strdup (name)) == NULL)
			return NULL;
		hashval = hash (name);
		np -> next = hashtab[hashval];
		hashtab[hashval] = np;
	}else
		free ((void *) np -> name);
	if (( np -> name = strdup(name)) == NULL)
		return NULL;
	return np;
}
so to summarize i am confused as to how to implement the install func so when the slot in the hashtable is free it inserts the word, and if it is occupied it simply adds another one in there.