1. #include "stdio.h"
    2. #include "stdlib.h"
    3. #include "io.h"
    4. #include "math.h"
    5. #include "time.h"
    6. #define OK 1
    7. #define ERROR 0
    8. #define TRUE 1
    9. #define FALSE 0
    10. #define MAXSIZE 100 /* 存储空间初始分配量 */
    11. #define SUCCESS 1
    12. #define UNSUCCESS 0
    13. #define HASHSIZE 12 /* 定义散列表长为数组的长度 */
    14. #define NULLKEY -32768
    15. typedef int Status; /* Status是函数的类型,其值是函数结果状态代码,如OK等 */
    16. typedef struct
    17. {
    18. int *elem; /* 数据元素存储基址,动态分配数组 */
    19. int count; /* 当前数据元素个数 */
    20. }HashTable;
    21. int m=0; /* 散列表表长,全局变量 */
    22. /* 初始化散列表 */
    23. Status InitHashTable(HashTable *H)
    24. {
    25. int i;
    26. m=HASHSIZE;
    27. H->count=m;
    28. H->elem=(int *)malloc(m*sizeof(int));
    29. for(i=0;i<m;i++)
    30. H->elem[i]=NULLKEY;
    31. return OK;
    32. }
    33. /* 散列函数 */
    34. int Hash(int key)
    35. {
    36. return key % m; /* 除留余数法 */
    37. }
    38. /* 插入关键字进散列表 */
    39. void InsertHash(HashTable *H,int key)
    40. {
    41. int addr = Hash(key); /* 求散列地址 */
    42. while (H->elem[addr] != NULLKEY) /* 如果不为空,则冲突 */
    43. {
    44. addr = (addr+1) % m; /* 开放定址法的线性探测 */
    45. }
    46. H->elem[addr] = key; /* 直到有空位后插入关键字 */
    47. }
    48. /* 散列表查找关键字 */
    49. Status SearchHash(HashTable H,int key,int *addr)
    50. {
    51. *addr = Hash(key); /* 求散列地址 */
    52. while(H.elem[*addr] != key) /* 如果不为空,则冲突 */
    53. {
    54. *addr = (*addr+1) % m; /* 开放定址法的线性探测 */
    55. if (H.elem[*addr] == NULLKEY || *addr == Hash(key)) /* 如果循环回到原点 */
    56. return UNSUCCESS; /* 则说明关键字不存在 */
    57. }
    58. return SUCCESS;
    59. }
    60. int main()
    61. {
    62. int arr[HASHSIZE]={12,67,56,16,25,37,22,29,15,47,48,34};
    63. int i,p,key,result;
    64. HashTable H;
    65. key=39;
    66. InitHashTable(&H);
    67. for(i=0;i<m;i++)
    68. InsertHash(&H,arr[i]);
    69. result=SearchHash(H,key,&p);
    70. if (result)
    71. printf("查找 %d 的地址为:%d \n",key,p);
    72. else
    73. printf("查找 %d 失败。\n",key);
    74. for(i=0;i<m;i++)
    75. {
    76. key=arr[i];
    77. SearchHash(H,key,&p);
    78. printf("查找 %d 的地址为:%d \n",key,p);
    79. }
    80. return 0;
    81. }