首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在C语言中实现字典的快速方法

在C语言中实现字典的快速方法
EN

Stack Overflow用户
提问于 2018-04-23 08:34:23
回答 2查看 0关注 0票数 0

我在C程序中错过的一件事是字典数据结构。用C实现一个最方便的方法是什么?我不是在寻找性能,而是从头开始轻松编写代码。我不希望它是通用的 - 类似string-> int会做。但我确实希望它能够存储任意数量的项目。

这更像是一个练习。我知道有第三方库可供使用。但是暂时考虑一下,他们不存在。在这种情况下,你可以用最快的方法来实现满足上述要求的字典。

EN

回答 2

Stack Overflow用户

发布于 2018-04-23 17:10:11

The C Programming Language的 6.6节介绍了一个简单的字典(散列表)数据结构。我不认为有用的字典实现可能比这更简单。为了您的方便,我在这里重现了代码。

代码语言:javascript
复制
struct nlist { /* table entry: */
    struct nlist *next; /* next entry in chain */
    char *name; /* defined name */
    char *defn; /* replacement text */
};

#define HASHSIZE 101
static struct nlist *hashtab[HASHSIZE]; /* pointer table */

/* hash: form hash value for string s */
unsigned hash(char *s)
{
    unsigned hashval;
    for (hashval = 0; *s != '\0'; s++)
      hashval = *s + 31 * hashval;
    return hashval % HASHSIZE;
}

/* lookup: look for s in hashtab */
struct nlist *lookup(char *s)
{
    struct nlist *np;
    for (np = hashtab[hash(s)]; np != NULL; np = np->next)
        if (strcmp(s, np->name) == 0)
          return np; /* found */
    return NULL; /* not found */
}

char *strdup(char *);
/* install: put (name, defn) in hashtab */
struct nlist *install(char *name, char *defn)
{
    struct nlist *np;
    unsigned hashval;
    if ((np = lookup(name)) == NULL) { /* not found */
        np = (struct nlist *) malloc(sizeof(*np));
        if (np == NULL || (np->name = strdup(name)) == NULL)
          return NULL;
        hashval = hash(name);
        np->next = hashtab[hashval];
        hashtab[hashval] = np;
    } else /* already there */
        free((void *) np->defn); /*free previous defn */
    if ((np->defn = strdup(defn)) == NULL)
       return NULL;
    return np;
}

char *strdup(char *s) /* make a duplicate of s */
{
    char *p;
    p = (char *) malloc(strlen(s)+1); /* +1 for ’\0’ */
    if (p != NULL)
       strcpy(p, s);
    return p;
}

请注意,如果两个字符串的散列发生冲突,则可能会导致O(n)查找时间。您可以通过增加值来减少碰撞的可能性HASHSIZE。有关数据结构的完整讨论,请参阅本书。

票数 0
EN

Stack Overflow用户

发布于 2018-04-23 18:24:31

最快的方法是使用一个已经存在的实现,像uthash

而且,如果您真的想自己编写代码,uthash则可以检查并重新使用算法。它是BSD许可的,除了要求传达版权声明之外,你可以用它做的事情无限制。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100003957

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档