#include #include struct nlist { struct nlist *next; char *name; char *defn; }; #define HASHSIZE 101 static struct nlist *hashtab[HASHSIZE]; /* hash */ unsigned hash(char *s) { unsigned hashval; for (hashval = 0; *s != '\0'; s++) hashval = *s + 31 * hashval; return hashval % HASHSIZE; } /* lookup */ 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; } /* install */ struct nlist *install(char *name, char *defn) { struct nlist *np; unsigned hashval; if ((np = lookup(name)) == NULL) { np = (struct nlist *)malloc(sizeof(*np)); if (np == NULL || (np->name = (char *)strdup(name)) == NULL) return NULL; hashval = hash(name); np->next = hashtab[hashval]; hashtab[hashval] = np; } else free((void *) np->defn); if ((np->defn = (char *)strdup(defn)) == NULL) return NULL; return np; } main() { struct nlist *np; install("apple", "RINGO"); np = lookup("apple"); printf("%s: %s\n", np->name, np->defn); exit(0); }