链地址的哈希表实现
1.類型定義
1 typedef struct Node { 2 RcdType r; 3 struct Node *next; 4 } Node; 5 typedef struct { 6 Node **rcd; 7 int size; // 哈希表容量 8 int count; // 當(dāng)前表中含有的記錄個數(shù) 9 int (*hash)(KeyType key, int); // 函數(shù)指針變量,用于選取的哈希函數(shù) 10 } HashTable; ?2.初始化
1 Status InitHash(HashTable &H, int size, int (*hash)(KeyType,int)) { 2 //初始化哈希表 3 int i; 4 if(NULL==(H.rcd=(Node**)malloc(sizeof(Node)*size))) return OVERFLOW; 5 for(i = 0;i<size;i++) 6 H.size = size; 7 H.count = 0; 8 H.hash = hash; 9 return OK; 10 } ?3.查找
1 Node* SearchHash(HashTable &H, int key){ 2 int p = H.hash(key,H.size); 3 Node *np; 4 for(np = H.rcd[p];np!=NULL;np=np->next){ 5 if(np->r.key = key) return np; 6 } 7 return NULL; 8 } 9 ? 10 ? 11 //哈希函數(shù) 12 int hash(int key, int size) { 13 return 3*key%size; 14 } 15 ??
?4.插入
1 Status InsertHash(HashTable &H, RcdType e){ 2 int p; 3 Node *np; 4 if((np=SearchHash(H, e.key))==NULL){ 5 p = H.hash(e.key, H.size); 6 np = (Node*)malloc(sizeof(Node)); 7 if(np==NULL) return OVERFLOW; 8 np->r = e; 9 np->next = H.rcd[p]; 10 H.rcd[p]= np; 11 H.count++; 12 return OK; 13 } 14 return error; 15 }?
??
?
轉(zhuǎn)載于:https://www.cnblogs.com/linwx/articles/7655603.html
《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
- 上一篇: xp sp3安装.Net 4.0提示严重
- 下一篇: 多线程之HttpClient