`
ackerman
  • 浏览: 72700 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

The C Programming Lang (K&R) hash table

 
阅读更多

hash.h

#include <stdio.h>
#define    HASHSIZE 101

struct nlist {
        struct nlist *next;
        char *name;
        char *defn;
};

unsigned hash(char *s);
struct nlist *lookup(char *s);
struct nlist *install(char *name, char *defn);
 

hash.c

#include <string.h>
#include "hash.h"

static struct nlist *hashtab[HASHSIZE];

unsigned hash(char *s)
{
        unsigned hashval;

        for (hashval = 0; *s != '\0'; s++)
                hashval = *s + 31 * hashval;
        return hashval % HASHSIZE;
}

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

struct nlist *install(char *name, char *defn)
{
        struct nlist *np;
        unsigned hashval;

        if ((np = lookup(name)) == NULL) {
                np = (struct nlist *)malloc(sizeof(struct nlist));
                if (np == NULL || (np->name = strdup(name)) == NULL)
                        return NULL;
                hashval = hash(name);
                np->next = hashtab[hashval];
                hashtab[hashval] = np;
        } else
                free((void *)np->defn);
        if ((np->defn = strdup(defn)) == NULL)
                return NULL;
        return np;
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics