当前位置:   article > 正文

C++哈希表实现_c++ 哈希表源码

c++ 哈希表源码

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<time.h>
  4. #define HASHLENGTH 10
  5. struct node
  6. {
  7. int data;
  8. struct node *next;
  9. };
  10. struct node hash[HASHLENGTH];
  11. typedef struct node * HashNode;
  12. int Hash(int k)
  13. {
  14. return k%HASHLENGTH;
  15. }
  16. void CreateHash()
  17. {
  18. for(int i=0; i<HASHLENGTH; i++)
  19. {
  20. hash[i].data = i;
  21. hash[i].next = NULL;
  22. }
  23. }
  24. void PrintOneLink(struct node h)
  25. {
  26. HashNode ptr = h.next;
  27. while(ptr != NULL)
  28. {
  29. printf("%d ", ptr->data);
  30. ptr = ptr->next;
  31. }
  32. printf("\n");
  33. }
  34. void PrintHash()
  35. {
  36. for(int i=0; i<HASHLENGTH; i++)
  37. {
  38. printf("hash[%d]:", i);
  39. PrintOneLink(hash[i]);
  40. }
  41. }
  42. bool SearchHash(int data)
  43. {
  44. int p = Hash(data);
  45. HashNode ptr = hash[p].next;
  46. while(ptr != NULL && ptr->data!=data)
  47. {
  48. ptr = ptr->next;
  49. }
  50. if(ptr == NULL)
  51. return false;
  52. return true;
  53. }
  54. int InsertHash(int data)
  55. {
  56. if(SearchHash(data)==true)
  57. {
  58. return 0;
  59. }
  60. else
  61. {
  62. int p = Hash(data);
  63. HashNode hn = (HashNode)malloc(sizeof(struct node));
  64. hn->data = data;
  65. hn->next = NULL;
  66. if(hash[p].next == NULL)
  67. {
  68. hash[p].next = hn;
  69. }
  70. else
  71. {
  72. hn->next = hash[p].next;
  73. hash[p].next = hn;
  74. }
  75. }
  76. return 1;
  77. }
  78. void DeleteHash(int data)
  79. {
  80. if(SearchHash(data)==true)
  81. {
  82. int p = Hash(data);
  83. HashNode ptr = hash[p].next;
  84. HashNode prePtr = ptr;
  85. if(ptr->data == data)
  86. {
  87. hash[p].next = ptr->next;
  88. free (ptr);
  89. }
  90. else
  91. {
  92. while(ptr != NULL && ptr->data != data)
  93. {
  94. prePtr = ptr;
  95. ptr = ptr->next;
  96. }
  97. prePtr->next = ptr->next;
  98. free(ptr);
  99. }
  100. }
  101. else
  102. {
  103. printf("Don't have the number\n");
  104. }
  105. }
  106. void HashTest()
  107. {
  108. CreateHash();
  109. int data = -99;
  110. srand( (unsigned)time(NULL) );
  111. for(int i=0; i<30; i++)
  112. {
  113. data = rand();
  114. InsertHash(data);
  115. }
  116. PrintHash();
  117. printf("Enter a number to delete:");
  118. while(scanf("%d", &data) != EOF)
  119. {
  120. DeleteHash(data);
  121. PrintHash();
  122. printf("Enter a number to delete:");
  123. }
  124. }
  125. int main()
  126. {
  127. HashTest();
  128. return 0;
  129. }


声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号