HashTable 是實務上最常被搬出來的資料結構之一。下面這個版本刻意保持精簡,但一個可用的雜湊表該有的環節——雜湊函式、桶陣列、衝突鏈表、查詢與釋放——都沒有缺席。
hashtable hashtable_new(int size); /* size 為桶(節點)數量 */ void hashtable_put(hashtable h, const char *key, void *val); void *hashtable_get(hashtable h, const char *key); void hashtable_delete_node(hashtable h, const char *key); void hashtable_free(hashtable h);
雜湊節點除了必要的 key 與 value,還有一個 next 用來串起同一桶內的衝突項:
typedef struct hashnode_struct {
struct hashnode_struct *next;
const char *key;
void *val;
} *hashnode, _hashnode;
雜湊表本體則由記憶體池統一管理,避免節點散落各處:
typedef struct hashtable_struct {
pool_t p; /* 記憶體池 */
int size;/* 桶空間大小 */
int count; /* 目前可用的節點數 */
struct hashnode_struct *z; /* 桶陣列 */
} *hashtable, _hashtable;
hashtable hashtable_new(int size)
{
hashtable ht;
pool_t p;
p = _pool_new_heap(sizeof(_hashnode) * size + sizeof(_hashtable));
ht = pool_malloc(p, sizeof(_hashtable));
ht->size = size;
ht->p = p;
ht->z = pool_malloc(p, sizeof(_hashnode) * size);
return ht;
}
邏輯很直白:先依 size 開一個夠大的記憶體池,再把表頭與桶陣列切出來。實務上 size 不妨估得寬鬆一些,能少幾次擴充。
寫入之前得先有雜湊函式。這裡採用經典的 ELF hash:
static int hashcode(const char *s, int len)
{
const unsigned char *name = (const unsigned char *)s;
unsigned long h = 0, g;
int i;
for (i = 0; i < len; i++) {
h = (h << 4) + (unsigned long)(name[i]);
if ((g = (h & 0xF0000000UL)) != 0)
h ^= (g >> 24);
h &= ~g; /* 清掉第 28~31 位 */
}
return (int)h;
}
接著才是 put 本身:
void hashtable_put(hashtable h, const char *key, void *val)
{
if (h == NULL || key == NULL) return;
int len = strlen(key);
int index = hashcode(key, len);
hashnode node = hashtable_node_get(h, key, len, index);
if (node != NULL) { /* 已存在則以新值覆蓋 */
node->key = key;
node->val = val;
return;
}
node = hashnode_node_new(h, index); /* 配置新節點 */
node->key = key;
node->val = val;
}
判斷鍵值是否已存在的工作交給 hashtable_node_get,作法就是把雜湊值取模定位到桶,再沿著衝突鏈表逐項比對:
static hashnode hashtable_node_get(hashtable h, const char *key,
int len, int index)
{
hashnode node;
int i = index % h->size;
for (node = &h->z[i]; node != NULL; node = node->next)
if (node->key != NULL && strlen(node->key) == len
&& strncmp(key, node->key, len) == 0)
return node;
return NULL;
}
先比長度再比內容,是個便宜又有效的小優化。剩下的刪除與釋放,不過是這套鏈表操作的反向流程。