【问题标题】:C - Initializing a hash tableC - 初始化哈希表
【发布时间】:2016-02-10 19:27:36
【问题描述】:

我正在学习结构和哈希表,并试图弄清楚如何将所有内容放在一起。我希望能够将单词添加到哈希表中,然后每次再次添加该单词时,它都会增加一个计数器而不是再次添加该单词。这是我目前所拥有的:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define HASH_MULTIPLIER 65599

struct NodeType
{
    char *word;
    int count;
    struct NodeType *next;
};
typedef struct NodeType Node;

unsigned int hash(const char *str);
Node **ht_create(void);

int htsize;

int main(int argc, char *argv[])
{
    if (argc <= 1)
    {
        printf("Please declare a table size");
        return 1;
    }
    htsize = atoi(argv[1]);
}

unsigned int hash(const char *str)
{
    int i;
    unsigned int h = OU;

    for (i = 0; str[i] != '\0'; i++)
        h = h * HASH_MULTIPLIER + (unsigned char) str[i];

    return h % htsize;
}

Node **ht_create(void)
{

}

所以这就是我卡住的地方。如果我想动态分配大小为htsize 的哈希表,是否只使用malloc 初始化一个数组?我真的迷路了,有人能指出我正确的方向吗?

【问题讨论】:

    标签: c arrays data-structures hashmap hashtable


    【解决方案1】:

    您的哈希表可能被定义为一个指针数组。数组中的每个条目都指向哈希到相同值的单词链接列表的开头。因此,您将使用 malloc 或 calloc 来创建指针数组。最初,它们都是 NULL,因为哈希表一开始是空的。

    【讨论】:

    • 所以看起来像char **Table = malloc(htsize);?
    • 关闭。你需要做类似 struct NodeType* Table = malloc(htsize * sizeof (struct NodeType *)); htsize 需要乘以该指针的大小。
    猜你喜欢
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 2012-03-20
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多