Skip to content

Commit 7747d3a

Browse files
committed
Hashing implementation with chaining collision resolution
1 parent 209a393 commit 7747d3a

File tree

1 file changed

+132
-0
lines changed

1 file changed

+132
-0
lines changed

Hashing/Chaining.cpp

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
#include<iostream>
2+
#include<math.h>
3+
using namespace std;
4+
struct node{
5+
int data;
6+
struct node *next;
7+
} *head[100],*curr;
8+
9+
void init(){
10+
for(int i=0;i<100;i++)
11+
head[i]=NULL;
12+
}
13+
14+
void add(int x,int h){
15+
struct node *temp = new node;
16+
temp->data = x;
17+
temp->next = NULL;
18+
if(head[h]==NULL){
19+
head[h] = temp;
20+
curr=head[h];
21+
}
22+
else{
23+
curr=head[h];
24+
while(curr->next!=NULL)
25+
curr=curr->next;
26+
curr->next = temp;
27+
}
28+
}
29+
30+
void display(int mod){
31+
struct node *temp;
32+
int i;
33+
for(i=0;i<mod;i++){
34+
if(head[i]==NULL){
35+
cout<<"Key = "<<i<<" is empty"<<endl;
36+
}
37+
else{
38+
cout<<"Key = "<<i<<" Value = ";
39+
temp = head[i];
40+
while(temp->next!=NULL){
41+
cout<<temp->data<<" ";
42+
temp=temp->next;
43+
}
44+
cout<<temp->data;
45+
cout<<endl;
46+
}
47+
}
48+
}
49+
50+
int hash(int x,int mod){
51+
return x%mod;
52+
}
53+
54+
void find(int x,int h){
55+
struct node *temp =head[h];
56+
if(head[h]==NULL){
57+
cout<<"Element not found";
58+
return;
59+
}
60+
while(1){
61+
if(temp->data==x)
62+
break;
63+
else if(temp->next==NULL)
64+
break;
65+
temp=temp->next;
66+
}
67+
if(temp->next!=NULL)
68+
cout<<"Element found";
69+
else{
70+
if(temp->data==x)
71+
cout<<"Element found";
72+
else
73+
cout<<"Element not found";
74+
}
75+
}
76+
77+
int main(void){
78+
init();
79+
int c,x,mod;
80+
cout<<"Enter the size of Hash Table. = ";
81+
cin>>mod;
82+
while(1){
83+
cout<<endl;
84+
cout<<"PLEASE CHOOSE -"<<endl;
85+
cout<<"1. Add element."<<endl;
86+
cout<<"2. Find element."<<endl;
87+
cout<<"3. Generate Hash."<<endl;
88+
cout<<"4. Display Hash table."<<endl;
89+
cout<<"5. Exit."<<endl;
90+
cin>>c;
91+
switch(c){
92+
case 1:{
93+
cout<<"Enter element to add = ";
94+
cin>>x;
95+
int h = hash(x,mod);
96+
if(h<0)
97+
h=fabs(h);
98+
add(x,h);
99+
break;
100+
}
101+
case 2:{
102+
cout<<"Enter element to search = ";
103+
cin>>x;
104+
int h=hash(x,mod);
105+
find(x,h);
106+
break;
107+
}
108+
case 3:{
109+
cout<<"Enter element to generate hash = ";
110+
cin>>x;
111+
cout<<"Hash of "<<x<<" is = "<<hash(x,mod);
112+
break;
113+
}
114+
case 4:{
115+
display(mod);
116+
}
117+
default:{
118+
break;
119+
}
120+
}
121+
if(c>4)
122+
break;
123+
cout<<endl;
124+
}
125+
/*add(1,&head1);
126+
add(2,&head1);
127+
add(3,&head2);
128+
add(5,&head1);
129+
display(&head1);
130+
display(&head2);*/
131+
return 0;
132+
}

0 commit comments

Comments
 (0)