Reputation: 1692
I am trying to retrieve a linked list from a hash table.
My code right now only grabs the first node of the linked list. How do I get the whole list? And what the return type should be?
So I have a struct
representing an entry:
typedef struct Entry {
char *word;
int len;
struct Entry *next;
} Entry;
And I make a array of those entries as my table (And I do malloc spaces for each element of the table in my program):
struct Entry *table[TABLE_SIZE] = { NULL }; // an array of elements
This is my get function. It receives the hash value, then returns the linked list at that location. I believe I need a loop here but I don't really know how to implement it.
struct Entry* getList(int h) {
// Return linked list
return table[h];
}
Upvotes: 1
Views: 1479
Reputation: 528
Hash tables are unordered, so if you're allowing duplicate entries, the value returned is usually unspecified. Returning an entire list may not make sense, since values that hash to the same location are not necessarily equal, or related in any way (depends on the data and hash function).
Hash tables use two functions. The first is for hashing, the second is for equality. What you probably want is something like the following.
Entry* find_entry(const char* key)
{
int hpos = hasher(key) % TABLE_SIZE;
Entry* p;
for (p = table[hpos]; p != NULL; p = p->next)
if (is_equal(p->word, key))
return p;
return NULL;
}
Upvotes: 4