#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define NHASH 30 /* the maxsize of array*/
typedef struct Nameval Nameval;
struct Nameval
{
char *name;
int value;
Nameval *next;/* in chain*/
};
Nameval *symtab[NHASH]; /* a symbol table*/
Nameval *lookup(char *name,int create,int value);
unsigned int hash(char *str);
void apply(Nameval *sym,void (*fn)(Nameval *,void *),void *arg);
void printnv(Nameval *sym,void *arg);
int main()
{
Nameval *sym=NULL;
char *name;
int create,value,i;
for(i=0;i<30;i++)
symtab[i]=NULL;
for(i=0;i<8;i++)
{
name=(char *)malloc(sizeof(char));
if(!name)return NULL;
scanf("%s",name);
scanf("%d",&create); //注意一般输入1
scanf("%d",&value);
sym=lookup(name,create, value);
}
printf("------------------------/n");
apply(sym,printnv," %s:%d/n");
printf("------------------------/n");
return 1;
}
/* lookup: find name in symtab, with optional create*/
Nameval *lookup(char *name,int create,int value)
{
int h;
Nameval *sym;
h=hash(name);
for(sym=symtab[h]; sym !=NULL; sym=sym->next)
if (strcmp(name, sym->name)==0)
return sym;
if(create){
sym=(Nameval *)malloc(sizeof(Nameval));
if(!sym) return NULL;
sym->name=name;/* assumed allocated elsewhere*/
sym->value=value;
sym->next=symtab[h];
symtab[h]=sym;
}
return sym;
}
/*apply:execute fn for each element of listp*/
void apply(Nameval *sym,void (*fn)(Nameval *,void *),void *arg)
{
int i;
for( i=0; i<NHASH; i++)
for(sym=symtab[i]; sym !=NULL; sym=sym->next)
(*fn)(sym,arg); /*call the function*/
}
/*printnv:print name and value using format int arg*/
void printnv(Nameval *sym,void *arg)
{
char *fmt;
fmt=(char *)arg;
printf(fmt,sym->name,sym->value);
}
enum{MULTIPLIER =31};
/*hash : compute hash value of string */
unsigned int hash(char *str)
{
unsigned int h;
unsigned char *p;
h=0;
for(p= (unsigned char *)str; *p !='/0'; p++)
h= MULTIPLIER * h + *p;
return h%NHASH;
}