1
votes

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];
}
1
Unless I'm misunderstanding something, there's no such thing as "the whole list". The list is just all the nodes in it. - user253751
What is value of next of the entry that getList returns? - Andrey
When I say the whole list, I meant every nodes in the list. next returns a pointer to the next node. - PTN
The idea of the typedef is that you can write Entry in stead of struct Entry. Otherwise you are doing right. The return value of getList is a pointer to your list as well as a pointer to the first node. - Mikkel Christiansen
Ah got it so I just need a loop and use the next pointer then. I thought table[h] only gives you the first node. - PTN

1 Answers

4
votes

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;
}