Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

Hash Table Operations

User image

Published by

sanya sanya

Published at: 6th Aug, 2023
1.485 mins read

Several operations can be performed on hash tables. We will discuss each of them.

  1. Create a hash table: To create a hash table, a node with key and value is required and a hash table that contains addresses of node*.

Hash functions can be coded in several ways. In the following code, we use the basic method in which key is multiplied with a prime number and it’s modulus with total size of array is taken.

Code:

class node{

public:

string key;

int val;

node*next;

node(string k, int v){

val=v;

key=k;

next=NULL;

}

};

class hashmap{

int total_size;

int cur_size;

node**arr;

public:

hashmap(int size){

cur_size=0;

total_size=size;

arr=new node*[total_size];

for(int i=0;i<total_size;i++){

arr[i]=NULL;

}

}

};

int hashfunction(string key){

int ans=0;

int mul=1;

for(int i=0;i<key.length();i++){

ans+=(key[i]%total_size*mul%total_size)%total_size;

mul=(mul*29)%total_size;

}

ans=ans%total_size;

return ans;

}

}

  1. Searching in a hash table: The main need for hashing is to search and access elements in constant time.

Code:

node*search(string key){

int index=hashfunction(key);

node*head=arr[index];

while(head){

if(head->key==key){

return head;

}

head=head->next;

}

return NULL;

}

  1. Insert in a hash table: This inserts a new key-value pair in hash table in order to store data.

Code: ** void insert (string key, int val){

int index=hashfunction(key);

node*n=new node(key, val);

n->next=arr[index];

arr[index]=n;

cur_size++;

}

  1. Delete a key in hash table: This deletes a key-value pair from hash table.

Code:

void deleteKey (int key){

node* it= search(key);

delete it;

}

  1. Delete hash table: Table can be deleted either using destructor or a different function.

Code:

void deleteTable(){

//Delete all nodes and arrays

for(int i=0; i< total_size; ++i){

node*cur=arr[i];

while(cur!=NULL){

node*temp=cur;

cur=cur->next;

delete temp;

}

}

delete[] arr;

}

Library

WEB DEVELOPMENT

FAANG QUESTIONS