字典的散列法表示。

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef int KeyType;
  4. typedef int DataType;
  5. typedef struct 
  6. {
  7.     KeyType key;
  8.     DataType value;
  9. } DicElement;
  10. typedef struct 
  11. {
  12.     int m;
  13.     DicElement *element;
  14. } HashDictionary;
  15. typedef HashDictionary * PHashDictionary;
  16. ///散列表的初始化。
  17. PHashDictionary createEmptyDictionary(int m)
  18. {
  19.     int i;
  20.     PHashDictionary phd = (PHashDictionary)malloc(sizeof(HashDictionary));
  21.     if(phd != NULL){
  22.         phd -> element = (DicElement *)malloc(sizeof(DicElement) * m);
  23.     if(phd ->element != NULL)
  24.     {
  25.         phd ->m = m;
  26.         for(i = 0; i < m; i++)
  27.             phd -> element[i].key = 0;
  28.         return phd;
  29.     }
  30.     else 
  31.         free(phd);
  32.     }
  33.     printf("Out of Space!/n");
  34.     return NULL;
  35. }
  36. ///散列函数。
  37. int h(KeyType key)
  38. {
  39.     return key % 13;
  40. }
  41. ///用先性探查法解决碰撞。
  42. int linearSearch(HashDictionary *phash, KeyType key, int *position)
  43. {
  44.     int d, inc;
  45.     d =h(key);
  46.     
  47.     for(inc = 0; inc < phash ->m; inc ++){
  48.         if(phash ->element[d].key == key){
  49.             *position = d;
  50.             return 1;
  51.         }
  52.         else if(phash ->element[d].key == 0){
  53.             *position = d;
  54.             return 0;
  55.         }
  56.         d = (d + 1)%phash ->m;
  57.     }
  58.     *position = -1; 
  59.     return 0;
  60. }
  61. int main(int argc, char **argv)
  62. {
  63.     PHashDictionary phd = createEmptyDictionary(13);
  64.     int position  = 0;
  65.     printf("%d/t%d/t%d/nposition = %d/n", position, phd ->element[9].key, phd->element[0].value, linearSearch(phd, 123, &position));
  66.     printf("d = %d/n", position);
  67.     return 0;
  68. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值