I am stuck on the load function for speller. I don't quite understand how to insert word into a linked list. This is what I have so far:
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
// open dictionary
FILE* dict = fopen(dictionary, "r");
if (dict = NULL)
{
return false;
}
}
// create array for word to be stored
char word[LENGTH + 1];
//scan through dictionary and load each word into hash table
while (fscanf(dict, "%s", word) != EOF)
{
// allocate memory for newWord
node *new_node = malloc(sizeof(node));
if (new_node == NULL)
{
printf("could not malloc a new node.\n");
fclose(dict);
return false;
}
//put word in new_node
strcpy(new_node->word, word);
//hash word and point head to it
int head = hash(word);
//insert word into linked list
//make new_node point to head, then head to new_node
new_node->next = head;
head = new_node;
}
Having looked at other people's code, it looks like I am missing an if function that goes something like this:
if (hashtable[head] == NULL)
{
hashtable[head] = new_node;
new_node->next = NULL;
}
else
{
new_node->next = hashtable[head];
hashtable[head] = new_node;
}
Can someone explain why this if function is necessary? Specifically, I don't understand these lines:
if (hashtable[head] == NULL)
{
hashtable[head] = new;
new->next = NULL;
Aren't head
and hashtable[head]
the same thing? if so how can head be null if we have just hashed it? And why would we want to make new_node->next
Null?
Thanks,