C++ program for hashing with chaining


Hashing is the method by which we can map any length data element to a fixed size key. hashing works as key-value pairs.

Hashing function is the function that does the mapping in a hash map. the data elements that are given as input to the Hash Function may get same hash key. In this case the elements may overlap. To avoid overlapping of elements which have the same hash key the concept of chaining was introduced.

Creating a hashmap

In order to create a hashmap we need hashing function that will define the index value of the data element.

We have a hash table, with n buckets. To insert a node into a hash table, we are given a hash function as

hashIndex = key % noOfBuckets

Now, we will use this hash function and calculate the hashindex of every inserted value to the hashmap.

  • Insert element and calculate the hashIndex of given key value and then insert the new node to the end of the list.

  • To delete a node, we will calculate the hash index and in the bucket corresponding to hash Index we will search for the element in the bucket and remove it.

Example

 Live Demo

#include<iostream>
#include <list>
using namespace std;
class Hash{
   int BUCKET;
   list < int >*table;
   public:
   Hash (int V);
   void insertItem (int x);
   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;
   }
}
 int main (){
   int a[] = { 5, 12, 67, 9, 16 };
   int n = 5;
   Hash h (7);
   for (int i = 0; i < n; i++)
   h.insertItem (a[i]);
   h.deleteItem (12);
   h.displayHash ();
   return 0;
}

Output

0
1
2 --> 9 --> 16
3
4 --> 67
5 --> 5
6

Updated on: 19-Sep-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements