fork download
  1. // CPP program to implement hashing with chaining
  2. #include<iostream>
  3. #include <list>
  4. using namespace std;
  5.  
  6. class Hash
  7. {
  8. int BUCKET; // No. of buckets
  9.  
  10. // Pointer to an array containing buckets
  11. list<int> *table;
  12. public:
  13. Hash(int V); // Constructor
  14.  
  15. // inserts a key into hash table
  16. void insertItem(int x);
  17.  
  18. // deletes a key from hash table
  19. void deleteItem(int key);
  20.  
  21. // hash function to map values to key
  22. int hashFunction(int x) {
  23. return (x % BUCKET);
  24. }
  25.  
  26. void displayHash();
  27. };
  28.  
  29. Hash::Hash(int b)
  30. {
  31. this->BUCKET = b;
  32. table = new list<int>[BUCKET];
  33. }
  34.  
  35. void Hash::insertItem(int key)
  36. {
  37. int index = hashFunction(key);
  38. table[index].push_back(key);
  39. }
  40.  
  41. void Hash::deleteItem(int key)
  42. {
  43. // get the hash index of key
  44. int index = hashFunction(key);
  45.  
  46. // find the key in (inex)th list
  47. list <int> :: iterator i;
  48. for (i = table[index].begin();
  49. i != table[index].end(); i++) {
  50. if (*i == key)
  51. break;
  52. }
  53.  
  54. // if key is found in hash table, remove it
  55. if (i != table[index].end())
  56. table[index].erase(i);
  57. }
  58.  
  59. // function to display hash table
  60. void Hash::displayHash() {
  61. for (int i = 0; i < BUCKET; i++) {
  62. cout << i;
  63. for (auto x : table[i])
  64. cout << " --> " << x;
  65. cout << endl;
  66. }
  67. }
  68.  
  69. // Driver program
  70. int main()
  71. {
  72. // array that contains keys to be mapped
  73. int a[] = {19, 26, 13, 48, 17};
  74. int n = sizeof(a)/sizeof(a[0]);
  75.  
  76. // insert the keys into the hash table
  77. Hash h(7); // 7 is count of buckets in
  78. // hash table
  79. for (int i = 0; i < n; i++)
  80. h.insertItem(a[i]);
  81.  
  82. // delete 12 from hash table
  83. h.deleteItem(12);
  84.  
  85. // display the Hash table
  86. h.displayHash();
  87.  
  88. return 0;
  89. }
Success #stdin #stdout 0s 4500KB
stdin
Standard input is empty
stdout
0
1
2
3 --> 17
4
5 --> 19 --> 26
6 --> 13 --> 48