20) Write a cpp program to demonstrate the Hashing
#include<iostream>
#include<stdlib.h>
using namespace std;
#define max 100
typedef struct list
{
int data;
struct list *next;
}node;
node *ptr[max],*root[max],*temp[max];
class dic
{
public:
int index;
dic()
{
index=-1;
for(int i=0;i<=max;i++)
{
root[i]=NULL;
ptr[i]=NULL;
temp[i]=NULL;
}
}
void insert(int key)
{
index=int(key%max);
ptr[index]=new node;
ptr[index]->data=key;
if(root[index]==NULL)
{
root[index]=ptr[index];
root[index]->next=NULL;
temp[index]=ptr[index];
}
else
{
temp[index]=root[index];
while(temp[index]->next!=NULL)
temp[index]=temp[index]->next;
temp[index]->next=ptr[index];
}
void search(int key)
{
int flag=0;
index=int(key%max);
temp[index]=root[index];
while(temp[index]->data==key)
{
if(temp[index]->data==key)
{
cout<<"\n search key is found";
flag=1;
break;
}
else
temp[index]=temp[index]->next;
}
if (flag=0)
cout<<"searched key not found";
}
void delete_ele(int key)
{
index=int(key%max);
temp[index]=root[index];
while(temp[index]->data!=key&&temp[index]!=NULL)
{
ptr[index]=temp[index];
temp[index]=temp[index]->next;
}
ptr[index]->next=temp[index]->next;
cout<<"\n"<<temp[index]->data<<"has been deleted";
temp[index]->data=-1;
temp[index]=NULL;
free(temp[index]);
}
};
int main()
{
int val,ch,n,num;
char c;
dic d;
do
{
cout<<"\n Menu \n1.create \n2.search \n3.delete \n4.exit";
cout<<"\n enter your choice:";
cin>>ch;
switch(ch)
{
case 1:
cout<<"\n enter the no of elements to be instered";
cin>>n;
cout<<"enter the elements to be inserted";
for(int i=0;i<n;i++)
{
cin>>num;
d.insert(num);
}
break;
case 2:
cout<<"enter the elements to be serached";
cin>>n;
d.search(n);
break;
case 3:
cout<<"enter the elements to be deleted";
cin>>n;
d.delete_ele(n);
break;
case 4:
exit(0);
default:
cout<<"invalid choice";
}
} while(ch<=4);
}