As I am searching dictionary example in C, I have come accross the example in here stackoverflow which references K&R The C Programming Language book. In that book, there is a table lookup topic in section 6.6. The section exemplifies table lookup as a hash table.
在本例中,哈希表由101个大小为nlist
(以下代码段中的 struct )的自引用 node 组成.
我的问题是,为什么他们在查找表中使用自引用 struct ?查找表作为键值对工作,所以我们不必保留下一个 node .
struct nlist {
/* table entry: */
struct nlist *next; /* next entry in chain */
char *name; /* defined name */
char *defn; /* replacement text */
};
我的问题的第二部分与示例有关,是关于lookup(char *s)
函数中的循环语句.这个循环只工作一次,而且可能与此无关,我想可能是我错过了什么!
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 */
}
我问题的最后一部分是关于函数*install(char *name, char *defn)
中的赋值np->next = hashtab[hashval];
(下面的函数),实际上它将当前 node 分配给自己作为下一个 node .
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;
}
提前谢谢.