c_cpp c中非常简单的哈希表

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp c中非常简单的哈希表相关的知识,希望对你有一定的参考价值。

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


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

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

/* 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 */
}


/* 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 = strduplicate(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 = strduplicate(defn)) == NULL)
       return NULL;
    return np;
}



int main(int argc, char const *argv[])
{
    install("foo", "doo");
    printf("foo is %s\n", lookup("foo")->defn);
    return 0;
}

以上是关于c_cpp c中非常简单的哈希表的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp C中的哈希表环境类

c_cpp c中的快速哈希表实现。

c_cpp 哈希表实现

c_cpp 为字符串实现哈希表和哈希函数

c_cpp 为字符串实现哈希表和哈希函数

c_cpp 在C中的哈希表,它可以解决重复问题。