- static hashnode hashnode_node_new(hashtable h, int index)
- {
- hashnode node;
- int i = index % h->size;
- h->count++;
- for(node = &h->z[i]; node != NULL; node = node->next)
- if(node->key == NULL) //这里的处理是:如果在HASH桶中存在某个值,KEY是空的,表明这个值已经没有用了,就用它来替换为现在准备写入的新接点。
- return node;
- node = pool_malloc(h->p, sizeof(_hashnode)); // 新建一个接点
- node->next = h->z[i].next; // 加入到桶中,就是加到链表的第一个接点。
- h->z[i].next = node;
- return node;
- }
根据KEY从hashtable中获取接点,步骤是先根据KEY计算hash值,然后从hashtable中找到指定的接点或者接点链表。如下:
- void *hashtable_get(hashtable h, const char *key)
- {
- if(h == NULL || key == NULL)
- <SPAN> </SPAN>return NULL;
- hashnode node;
- int len = strlen(key);
- if(h == NULL || key == NULL || len <= 0 || (node = hashtable_node_get(h, key, len, hashcode(key,len))) == NULL)
- {
- return NULL;
- }
- return node->val;
- }
六,释放HASHTABLE
hashtable的释放就比较简单了,因为我们所有的内存申请都在内存池上完成的,就只需要释放内存池,如下:
- void hashtable_free(hashtable h)
- {
- if(h != NULL)
- pool_free(h->p);
- }
七,释放单个hash接点
代码如下:
- void hashtable_delete_node(hashtable h, const char *key)
- {
- if(h == NULL || key == NULL)
- return;
- hashnode node;
- int len = strlen(key);
- if(h == NULL || key == NULL || (node = hashtable_node_get(h, key, len, hashcode(key,len))) == NULL) //没有这个接点
- return;
- node->key = NULL;
- node->val = NULL;
- h->count--;
- }
八,hashtable的遍历讨论
直接用数组,就是hashtable中的struct hashnode_struct数组是可以遍历,但如果只包含一个接点,也要遍历所有的数组,如下遍历:
- void hashtable_traverse(hashtable h)
- {
- int i;
- hashnode node;
- if(h == NULL)
- return;
- for(i = 0; i < h->prime; i++)
- for(node = &h->z[i]; node != NULL; node = node->next)
- if(node->key != NULL && node->val != NULL)
- XXXXXXXXXXXXXXXXX // 这里是一些操作。
- }
需要对前面hashtable数据结构做简单的改动,增加两个域:
- typedef struct hashtable_struct{
- pool_t p;
- int size;
- int count;
- struct hashnode_struct *z;
- int bucket;
- hashnode node;
- }*hashtable,_hashtable;
- node表示当前遍历的游标,在遍历过程中,不断的移动这个接点所指向的接点。
- bucket是和node相关联的,用于记录当前的node在哪个桶上。
首先建立连接,就是将所有的接点都连接起来,按照惯例,也采用XXX_iter_first函数,先初始化,如下:
- int hashtable_iter_first(hashtable h) {
- if(h == NULL)
- return 0;
- h->bucket = -1;
- h->node = NULL;
- return hashtable_iter_next(h);
- }
- int xhash_iter_next(xht h) {
- if(h == NULL) return 0;
- while(h->node != NULL) {
- h->node = h->node->next; // 移向下一个接点,如果接点合法,返回成功
- if(h->node != NULL && h->node->key != NULL && h->node->val != NULL)
- return 1;
- }
- for(h->bucket++; h->bucket < h->prime; h->bucket++) {
- h->node = &h->z[h->bucket];
- while(h->node != NULL) {
- if(h->node->key != NULL && h->node->val != NULL)
- return 1;
- h->node = h->node->next;
- }
- }
- h->bucket = -1; // 不存在下一个接点。
- h->node = NULL;
- return 0;
- }
- hashtable ht
- if(hashtable_iter_first(ht)) //取第一个接点。
- do{
- // 此时可以处理ht->node,表示当前的接点。
- }while(hashtable_iter_next(ht)); //取下一个接点
假如被删除的接点为node,需要如下处理:
- if(h->node == n)
- hashtable_iter_next(h);
