Skip to content

Instantly share code, notes, and snippets.

@baoqger
Created June 2, 2020 09:40
Show Gist options
  • Save baoqger/c2a5c8fd15f78b774271e184657cfaf1 to your computer and use it in GitHub Desktop.
Save baoqger/c2a5c8fd15f78b774271e184657cfaf1 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <list>
using namespace std;
class Hash {
int BUCKET;
list<int> *table; // pointer to an array containing buckets
public:
Hash(int V);
void insertItem(int key);
void deleteItem(int key);
int hashFunction(int x) {
return (x % BUCKET);
}
void displayHash();
};
Hash::Hash(int b) {
this->BUCKET = b;
table = new list<int>[BUCKET];
}
void Hash::insertItem(int key) {
int index = hashFunction(key);
table[index].push_back(key);
}
void Hash::deleteItem(int key) {
int index = hashFunction(key);
list <int> :: iterator i;
for (i = table[index].begin(); i != table[index].end(); i++) {
if (*i == key) {
break;
}
}
if (i != table[index].end()) {
table[index].erase(i);
}
}
void Hash:: displayHash() {
for (int i = 0; i < BUCKET; i++) {
cout << i;
for (auto x : table[i]) {
cout << "-->" << x;
}
cout << endl;
}
}
// Driver program
int main()
{
// array that contains keys to be mapped
int a[] = {15, 11, 27, 8, 12};
int n = sizeof(a)/sizeof(a[0]);
// insert the keys into the hash table
Hash h(7); // 7 is count of buckets in
// hash table
for (int i = 0; i < n; i++)
h.insertItem(a[i]);
// delete 12 from hash table
h.deleteItem(12);
// display the Hash table
h.displayHash();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment