哈希表·uthash遍历及示例分析 遍历从上面的struct UT_hash_handle可以看出当前节点记录了前后的prev和next。因此不断地迭代next值即可。void hash_print(struct MyHashNode *hashTable) { for (struct MyHashNode *it hashTable; it ! NULL; it it-hh.next) { printf(key %d value %d\n, it-key, it-value); } }示例下面通过一个综合示例对增删改查的效果进行演示。存入0~9的key和等值value将key为偶数的节点的value翻倍key为奇数的节点删除#include stdio.h #include uthash.h struct MyHashNode { int key; int value; // 必须定义名为 hh 的 UT_hash_handle UT_hash_handle hh; }; // 增 会修改原hashtable的结构 void hash_insert(struct MyHashNode **hashTable, struct MyHashNode *node) { HASH_ADD_INT(*hashTable, key, node); } // 删 会修改原hashtable的结构 void hash_erase(struct MyHashNode **hashTable, struct MyHashNode *node) { HASH_DEL(*hashTable, node); free(node); } // 改 void hash_modify(struct MyHashNode *node, int value) { node-value value; } // 查 struct MyHashNode *hash_find(struct MyHashNode *hashTable, int key) { struct MyHashNode *node NULL; HASH_FIND_INT(hashTable, key, node); return node; } // 遍历 void hash_print(struct MyHashNode *hashTable) { for (struct MyHashNode *it hashTable; it ! NULL; it it-hh.next) { printf(key %d value %d\n, it-key, it-value); } } int main(void) { const int n 10; struct MyHashNode *hashTable NULL; for (int i 0; i n; i 1) { struct MyHashNode *node malloc(sizeof(struct MyHashNode)); node-key i; node-value i; hash_insert(hashTable, node); } hash_print(hashTable); printf(*******************************************\n); for (int i 0; i n; i 1) { struct MyHashNode *node hash_find(hashTable, i); if (node ! NULL) { // 奇数节点删除 if (i 1) { hash_erase(hashTable, node); } // 偶数节点扩大两倍 else { hash_modify(node, node-value * 2); } } else { printf(hash find null\n); } } hash_print(hashTable); return 0; }当然uthash还为我们提供了正对指针字符串等元素作为键的操作。这些操作与整形数值的操作非常相似读者可以自行查看官方示例代码进行查看与学习。