《c程序设计语言》第6章结构,以“0,0”作为整个的起点
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define HASHSIZE 101
struct nlist {
struct nlist *next;
char *name;
char *defn;
};
static struct nlist *hashtab[HASHSIZE];
struct nlish *prev;
char *strdup2(char *s);
unsigned hash(char *s);
struct nlist *lookup(char *s);
struct nlist *last(void);
struct nlist *install(char *name, char *value);
void main(){
struct nlist *p;
struct nlist *np;
np = (struct nlist *)malloc(sizeof(*np));
np->name = "0";
np->defn = "0";
hashtab[hash("0")] = np;
install("a","aa");
install("b","bb");
install("c","bb");
p = lookup("b");
printf("%s\n", p->defn);
install("b","cc");
p = lookup("b");
printf("%s\n", p->defn);
p = lookup("c");
printf("%s\n", p->defn);
}
char *strdup2(char *s){
char *p;
p= (char *) malloc(strlen(s)+1);
if(p != NULL){
strcpy(p,s);
}
return p;
}
unsigned hash(char *s){
unsigned hashval;
for(hashval = 0; *s != '\0'; s++){
hashval = *s + 31*hashval;
}
return hashval % HASHSIZE;
}
struct nlist *lookup(char *s){
return hashtab[hash(s)];
}
struct nlist *last(){
struct nlist *p;
struct nlist *n;
p = lookup("0");
for(n = p; p == NULL; p = p->next){
n = p;
}
return n;
}
struct nlist *install(char *name, char *value){
struct nlist *np;
struct nlist *p;
unsigned hashval;
if((np = lookup(name)) != NULL){
free((void *)np->defn);
if((np->defn = strdup2(value)) == NULL){
return NULL;
}
} else {
np = (struct nlist *)malloc(sizeof(*np));
np->name = strdup2(name);
np->defn = strdup2(value);
hashtab[hash(name)] = np;
p = last();
p->next = np;
}
return np;
}