I am totally new to C so I am having troubles with hash table and linked list. I am making an anagram solver. There are many examples I found online but each person has done it differently and rather complicated so I'm really confused now.
I'm pretty okay with the most of the implementation of the program. But I'm actually stuck at the very beginning.
So I need to create a hash table where in each entry, the key is an int and the value is a linked list of words.
The way I get the key, or the hash value, is by converting a word to a number. For example, A is 1, B is 2, C is 3, AB is 3, BC is 5, ABC is 6, and so on. I guess the words should be case insensitive to make things easier.
Below is the code I'm working on. I'm pretty sure is not in the correct syntax. Right now I'm just working on the structure of the table.
typedef struct Entry {
int key;
char *word;
Entry *next;
} Entry;
typedef struct HashTable {
int size;
Entry *entry;
} HashTable;
// initialize table
HashTable* create(int size) {
HashTable *table = (HashTable *)malloc(sizeof(HashTable));
table->entry = (Entry *)malloc(sizeof(Entry) * size);
table->size = size;
int i;
for (i = 0; i < size; i++) {
table->entry[i].key = 0; // All entries to be 0
}
return table;
}
// hash the word
int getHash(char *word)
{
// How do I implement a loop here
}
void insert(HashTable *table, int key, char *word) {
int hash = getHash(word);
int i = 0;
// if key has already existed, find and add to linked list
while(table->entry[hash].key != 0 && (i < table->size)) {
if(table->entry[hash].key == key) {
table->entry[hash].word = word;
return; /* */
}
//hash = (hash + 1); // I'm also stuck with incrementing the hash value
i++; // increment loop index
}
// if key does not exist, find a '0 slot', and store the key and value
if(table->entry[hash].key == 0) {
table->entry[hash].key = key;
table->entry[hash].word = word;
}
}