I'm trying to create a program that reads a file that is filled with words in the dictionary, then stores every word in the hash table, I already have a hash function, for example the hash function returns an index 123
how will I be able to determine if that index right there has no value yet, else if the certain index has value should I just make the word the new head of the list or should I add it to the end of the list? Should I initialize the whole array first to something like "NULL" because if a variable wasn't initialized it contains garbage value, does that work the same with arrays from a struct..
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// Number of buckets in hash table
// N = 2 ^ 13
const unsigned int N = 8192;
// Hash table
node *table[N];
This is part of my code LENGTH here is defined above with the value of 45..
how will I be able to determine if that index right there has no value yet
The "slots" in your table are linked lists. The table
stores pointers to the head nodes of these linked lists. If that pointer is NULL
, the list is empty, but you don't need to make it a special case: When you look up a word, just walk the list while the pointer to the next node is not null. If the pointer to the head node is null, your walk is stopped short early, that's all.
should I just make the word the new head of the list or should I add it to the end of the list?
It shouldn't really matter. The individual lists at the nodes are supposed to be short. The idea of the hash table is to turn a linear search on all W
words into a faster linear search on W/N
words on average. If you see that your table has only a few long lists, your hash function isn't good.
You must walk the list once to ensure that you don't insert duplicates anyway, so you can insert at the end. Or you could try to keep each linked list alphabetically sorted. Pick one method and stick with it.
Should I initialize the whole array first to something like "NULL" because if a variable wasn't initialized it contains garbage value, does that work the same with arrays from a struct.
Yes, please initialize your array of head node pointers to NULL
, so that the hash table is in a defined state. (If your array is at file scope or static
, the table should be initialized to null pointers already, but it doesn't hurt to make the initialization explicit.)