在C中实现哈希表

时间:2012-05-20 21:44:44

标签: c pointers linked-list hashtable

我在C中实现一个简单的列表时遇到了麻烦,问题是通过指针连接项目 下面的一段代码是一个哈希表的片段,它应该在列表中存储具有相同索引的项目以避免冲突。

typedef struct dictEntry {
    void *key;
    void *value;
    struct dictEntry *next;
} dictEntry;

typedef struct dict {
    dictEntry **table;
    unsigned long size;
    unsigned long used;
} dict;

void dictAdd(dict *d, void *key, void *value) {
    int index = hash(key) & d->size;
    dictEntry *entry;

    entry = malloc(sizeof(entry));

    entry->key   = key;
    entry->value = value;
    entry->next  = 0;

    if (d->table[index]) {
        /* this is does not work */
        dictEntry *next;
        next = d->table[index];

        while (next) {
            next = next->next;
        }

        next = entry;
    } else {
        d->table[index] = entry;
        d->used++;
    }
}

我的想法是遍历列表中的每个元素(next->next)并将entry的指针指定给最后一个元素(next = entry;)。
经过几天的重写和移动部分代码后,我似乎仍无法找到解决方案。

3 个答案:

答案 0 :(得分:4)

您应该首先尝试实施链接列表。

以下是我如何实现添加到最后(我已经修改了你的代码,你只是覆盖临时" next"变量而不修改列表本身):

if (d->table[index]) {
    /* this should work*/
    dictEntry *next;
    dictEntry *prev = NULL;
    next = d->table[index];

    while (next) {
        prev = next;
        next = next->next;
    }

    // yes, add new entry as the "next" pointer to the "last" item
    prev->next = entry;
} else {

...

答案 1 :(得分:1)

entry = malloc(sizeof(entry));

应该是:

entry = malloc(sizeof *entry);

dictAdd也过于复杂。在这种情况下,使用指针指针将有所帮助:

void dictAdd(dict *d, void *key, void *value) {
    unsigned index;
    dictEntry **pp;

    index = hash(key) % d->size;
    if (!d->table[index]) d->used++;

    for (pp = &d->table[index]; *pp; pp = &(*pp)->next) {;}

    *pp = malloc(sizeof **pp);
     /* Omitted : handle ((*pp) == NULL) malloc failure here */
    (*pp)->key   = key;
    (*pp)->value = value;
    (*pp)->next  = NULL;
}  

答案 2 :(得分:0)

看看你的while循环。你要去next变为零,但你真的想要下一个指针为零的最后一个条目。修复它,它应该更接近。