C++ program to Implement Hash tables Chaining with Doubly Linked Lists
C++ program to Implement Hash tables Chaining with Doubly Linked lists
DESCRIPTION
A hash table is a data structure which is used to store key-value pairs. Hash function is used by hash table to compute an index into an array in which an element will be inserted or searched.
Implementing hash table using Chaining through Doubly Linked List . This will speed up the process of adding and removing elements from the list, hence the time complexity will be reduced drastically.
/SOURCE CODE/
#include<iostream>#include<stdbool.h> usingnamespacestd;
intconst tablesize = 10;
structhash_node
{int val,key;
hash_node *next;
hash_node *prev;
};
classHashchain
{public:
hash_node **hashtable, **top;
Hashchain()
{
hashtable= new hash_node*[tablesize];
top= new hash_node*[tablesize];
for(int i=0;i<tablesize;i++)
{
hashtable[i]=NULL;
top[i]=NULL;
}
}
intHashF(int key){
key % tablesize;
return key;
}
voidfind(int key){
int hash_val = HashF(key);
bool B = false;
hash_node* entry = hashtable[hash_val];
if (entry != NULL)
{
while (entry != NULL)
{
if (entry->key == key)
{
B = true;
}
if (B)
{
cout << "Element found at key "<< key << " is ";
cout << entry->val << endl;
}
entry = entry->next;
}
}
if (!B)
cout << "No Element found at key "
<< key << endl;
}
voidremove(int key){
int hash_val = HashF(key);
hash_node* entry = hashtable[hash_val];
if (entry->key != key || entry == NULL)
{
cout << "Couldnot find any element at this key "<< key << endl;
return;
}
while (entry != NULL)
{
if (entry->next == NULL)
{
if (entry->prev == NULL)
{
hashtable[hash_val] = NULL;
top[hash_val] = NULL;
delete entry; break;
}
else
{
top[hash_val] = entry->prev;
top[hash_val]->next = NULL;
delete entry;
entry = top[hash_val];
}
}
entry = entry->next;
}
cout << "Element was removed at the key "<< key << endl;
}
voidinsert(int key, int value){
int hash_val = HashF(key);
hash_node* entry = hashtable[hash_val];
if (entry == NULL)
{
entry = new hash_node;
entry->val = value;
entry->key = key;
entry->next = NULL;
entry->prev = NULL;
hashtable[hash_val] = entry;
top[hash_val] = entry;
}
else
{
while (entry != NULL)
entry = entry->next;
entry = new hash_node;
entry->val = value;
entry->key = key;
entry->next = NULL;
entry->prev = top[hash_val];
top[hash_val]->next = entry;
top[hash_val] = entry;
}
cout << "Value " << value << " was added at key " << key << endl;
}
};
intmain(){
Hashchain H;
H.insert(1,2);
H.find(1);
H.remove(1);
return0;
}
CONCLUSION
Thus the Implementation of Hash Tables chaining with doubly linked lists is CODED.
Comments