Advertisement
Guest User

Untitled

a guest
Aug 27th, 2016
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. #include "hash_tables.h"
  2.  
  3. struct element
  4. {
  5. int key;
  6. int value;
  7. };
  8.  
  9. struct hashTable
  10. {
  11. Element *table[11];
  12. };
  13.  
  14. int hash_function(int key)
  15. {
  16. return key%11;
  17. }
  18.  
  19. Hashtable* create_hash_table()
  20. {
  21. Hashtable *ht = (Hashtable*)malloc(sizeof(Hashtable));
  22. int i;
  23. for (i = 0; i < 11; i++)
  24. {
  25. ht->table[i] = NULL;
  26. }
  27. return ht;
  28. }
  29.  
  30. void put(Hashtable *ht, int key, int value)
  31. {
  32. int h = hash_function(key);
  33. while (ht->table[h] != NULL)
  34. {
  35. if (ht->table[h]->key == key)
  36. {
  37. ht->table[h]->value = value;
  38. break;
  39. }
  40. h = (h + 1) % 11;
  41. }
  42. if (ht->table[h] == NULL)
  43. {
  44. Element *new_element = (Element*) malloc(sizeof(Element));
  45. new_element->key = key;
  46. new_element->value = value;
  47. ht->table[h] = new_element;
  48. }
  49. }
  50.  
  51. int get(Hashtable *ht, int key)
  52. {
  53. int h;
  54. h = hash_function(key);
  55. while (ht->table[h] != NULL)
  56. {
  57. if (ht->table[h]->key == key)
  58. {
  59. return ht->table[h]->value;
  60. }
  61.  
  62. h = (h + 1) % 11;
  63. }
  64. return -100;
  65. }
  66.  
  67. void Remove(Hashtable *ht, int key)
  68. {
  69. int h;
  70. h = hash_function(key);
  71.  
  72. while (ht->table[h] != NULL)
  73. {
  74. if (ht->table[h]->key == key)
  75. {
  76. ht->table[h] = NULL;
  77. ht->table[h]->key = -1;
  78. }
  79. h = (h+1)%11;
  80. }
  81. }
  82.  
  83. int main()
  84. {
  85. Hashtable *ht = create_hash_table();
  86. put(ht, 3, 1000);
  87. put(ht, 14, 2000);
  88. put(ht, 15, 3000);
  89. put(ht, 92, 4000);
  90.  
  91. return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement