1
0

map.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. // 使用冲突链表实现的哈希表
  2. #ifndef LISTMAP
  3. #define LISTMAP
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6. int getPri(int n) {
  7. int primes[] = {
  8. 2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
  9. 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
  10. 73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
  11. 127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
  12. 179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
  13. 233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
  14. 283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
  15. 353, 359, 367, 373, 379, 383, 389, 397
  16. };
  17. int len = sizeof(primes) / sizeof(primes[0]);
  18. for (int i = len - 1; i >= 0; i--) {
  19. if (primes[i] < n) {
  20. return primes[i];
  21. }
  22. }
  23. return 1; // 如果n小于2,返回1
  24. }
  25. typedef struct List
  26. {
  27. int value;
  28. struct List *next;
  29. }List;
  30. typedef struct ListMap
  31. {
  32. int hash;
  33. int valid;
  34. int value;
  35. List *next;
  36. }ListMap;
  37. ListMap *createListMap(int n){
  38. int size = getPri(n);
  39. ListMap *map = (ListMap *)malloc(sizeof(ListMap)*size);
  40. if (map == NULL) {
  41. printf("Error: Memory allocation failed\n");
  42. return NULL;
  43. }
  44. // 初始化每个链表节点
  45. for (int i = 0; i < size; i++) {
  46. map[i].hash = size;
  47. map[i].valid = 0; // 初始状态
  48. map[i].value = 0; // 初始值
  49. map[i].next = NULL; // 初始指针
  50. }
  51. return map;
  52. }
  53. int hashCode(int key, int hash) {
  54. return key % hash;
  55. }
  56. static int get(ListMap *map, int key) {
  57. int hash = hashCode(key, map[0].hash);
  58. if(map[hash].valid == 0){
  59. return -1;
  60. }else{
  61. if(map[hash].value == key){
  62. return hash;
  63. }
  64. List *node = map[hash].next;
  65. while (node)
  66. {
  67. if(node->value == key){
  68. return hash;
  69. }
  70. node = node->next;
  71. }
  72. }
  73. return -1;
  74. }
  75. int insert(ListMap *map, int key) {
  76. int hash = hashCode(key, map[0].hash);
  77. if(get(map, key) != -1){
  78. return 2;
  79. }
  80. if(map[hash].valid == 0){
  81. map[hash].valid = 1;
  82. map[hash].value = key;
  83. }else{
  84. List *node = map[hash].next;
  85. while (node)
  86. {
  87. node = node->next;
  88. }
  89. List *newNode = (List *)malloc(sizeof(List));
  90. newNode->value = key;
  91. newNode->next = NULL;
  92. node->next = newNode;
  93. }
  94. return 1;
  95. }
  96. #endif
备用站点 当前处于降级运行的备用站点,仅供应急访问,数据和功能可能不是最新。