Skip to content

Commit f949083

Browse files
author
Christian Bender
authored
Merge pull request #92 from vasutomar/Hashing
Super! Keep it up!
2 parents 209a393 + f3f0e88 commit f949083

File tree

1 file changed

+123
-0
lines changed

1 file changed

+123
-0
lines changed

Hashing/Chaining.cpp

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

0 commit comments

Comments
 (0)