[英]I don't understand the hash tables example in K&R
這是來自K&R的書中哈希表示例的安裝函數:
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;
}
我不明白line np->next = hashtab[hasvall]
我認為變量np-> next的原因是為了在表中放入兩個具有相同散列值的字符串,但是這個結果只有每個哈希值的一個名稱。
此外,我似乎無法理解函數查找,以及“forfor中的AFTERTHOUGHT部分”(因為我認為每個結構中只有一個vaule:
/* 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 */
}
我錯過了什么?
每個值只能有一個鍵(名稱),但兩個或多個鍵可以具有相同的哈希值。 np->next = hashtab[hashval]
將新的hashval
添加到鏈表中。 然后查找遍歷列表,直到匹配鍵(名稱)。
np->next = hashtab[hashval];
hashtab[hashval] = np;
這兩行不會替換舊條目,它們會添加它。
hashtab[hashval]-> existing_node
成為
hashtab[hashval]-> np -(next)-> existing_node
正如@Bo Persson在評論中提到的那樣,這被稱為“ 鏈接 ”。
給定此結構, lookup
函數正確檢查鏈中每個節點的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.