1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
|
#include<iostream>
#include<math.h>
using namespace std;
// class node
class node{
public:
int id;
char * name;
char * address;
int age;
node * next;
int GPA;
node(int num,char * nam,char * addr,int ages,int gpa){
id = num;
name = nam;
address = addr;
age = ages;
GPA = gpa;}
};
// class Hash
class hash{
public : hash();
hash(int aa,int bb,int prime,int size);
~hash();
int hashfunc(int key);
bool insert(node *n);
bool retrieve(int id2,node *nn);
bool remove(int id3);
double getloadfactor();
int a ;int b;int p; int n;
node **table;
};
// constructers
hash::hash(){
a=23;b=88;n=100;p=997;
table=new node *[n];
for(int i=0;i<n;i++){
table [i]=NULL;}
};
hash::hash(int aa,int bb,int prime,int size){
a=aa;b=bb;p=prime;n=size;
table=new node *[n];
for( int i=0;i<n;i++){
table [i]=NULL;}
};
//destructers
hash::~hash(){
delete[] table;
/* node *p;
for(int j=0;j<n;j++)
while (table[j]!=NULL){
p=table[j];
table[j]=table[j]->next;
delete p;}
delete []table[j]; */
};
// hashing function
int hash::hashfunc(int key){
int H=((a*key+b)%p)%n;
return H;
}
// retrieve function
bool hash::retrieve(int id2,node *nn){
int s=hashfunc(id2);
bool done=true;
if(table[s]==NULL)done=false;
else{
node *pp=table[s];
while(pp!=NULL && !done){
if(pp->id==id2)
{
memcpy(nn,table[s],sizeof(node));
done = true;}
else{ pp=pp->next;}
}
}
return done;
}
// insert function
bool hash::insert(node *n){
bool done=false;
int F=hashfunc(n->id);
if(table[F]==NULL){
table[F]=n;
done=true;}
else{
n->next=NULL;
table[F]=n;
done=true;
}
return done;
}
// remove function
bool hash::remove(int id3){
node *p1,*p2;
bool done;
int m=hashfunc(id3);
p1=p2=table[m];
if(table[m]==NULL)done=true;
else if(table[m]->id==id3){
node *v=table[m];
table[m]=table[m]->next;
delete v;
done =true;
}
else {
while(p2!=NULL){
if(p2->id==id3){
p1->next=p2->next;
delete p2;
done = true;
}
else{ p1=p2;
p2=p2->next;}
}
}
return done;
}
// load function
double hash::getloadfactor(){
double count=0;
for(int u=0;u<n;u++){
if(table[u]!=NULL){
node *e=table[u];
while(e!=NULL){
count++;
e=e->next;}
}
}
return count/n;
}
int main(){
int gb=5; int gb1=7;int g=17;int num=9; int num1=5; int g1=12;
char *b="abdallah";
char *c="holyland";
char *b1="omar";
char *c1="america";
node d(num,b,c,g,gb);
node f(num1,b1,c1,g1,gb1);
int a1=1,b2=0,p1=5,n1=13;
hash i(a1,b2,p1,n1);
i.insert(d);
i.insert(f);
return 0;
}
|