#include<stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define MAXWORD 100
#define BUFSIZE 100
#define HASHSIZE 101
static struct nlist *hashtab[HASHSIZE]; /* pointer table指向结构体变量的指针数组 */
struct nlist { /* table entry: */
struct nlist *next; /* next entry in chain */
char *name; /* defined name */
char *defn; /* replacement text */
};
/*散列函数 hash 在 lookup 和 install 函数中都被用到,它通过一个 for 循环进行计
算,每次循环中,它将上一次循环中计算得到的结果值经过变换(即乘以 31)后得到的新值
同字符串中当前字符的值相加(*s + 31 * hashval),然后将该结果值同数组长度执行取
模操作,其结果即是该函数的返回值。*/
/* 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;
}
/* 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 */
}
struct nlist *lookup(char *);
char *strdup(char *);
/* install: put (name, defn) in hashtab */
/*install 函数借助 lookup 函数判断待加入的名字是否已经存在。如果已存在,则用新
的定义取而代之;否则,创建一个新表项。如无足够空间创建新表项,则 install 函数返回
NULL。*/
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 = strdup(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 = strdup(defn)) == NULL)
return NULL;
return np;
}
char *strdup(char *s) /* make a duplicate of s */
{
char *p;
p = (char *)malloc(strlen(s) + 1); /* +1 for '\0' */
if (p != NULL)
strcpy(p, s);
return p;
}