I programmed the below code to implement HashTable by Chains algorithm, but when i use it in main function, the result is wrong :
#define _SIZE 1000
class HashEntry
{
public: int Tel;
string Name;
public: HashEntry(){}
public: HashEntry(int Tel, string Name)
{
this->Tel = Tel;
this->Name = Name;
}
};
class Link {
public:
HashEntry data;
Link *next;
public:
Link() : next(NULL){ }
};
void Insert (Link *head, HashEntry data)
{
Link *t= new Link;
t->data=data;
if(head==NULL)
{
head = new Link;
head->next = NULL;
head->data = data;
return;
}
Link *head2= head;
while(head2->next!=NULL)
{
if( head2->data.Name == data.Name)
return;
head2=head2->next;
}
head2->next=t;
}
class HashTable {
public:
Link **a;
public:
HashTable()
{
a = new Link *[_SIZE];
for (int i=0; i<_SIZE; i++)
a[i]=NULL;
}
public:
int HashFonction (string key)
{
int res=0;
for ( int i = 0; i < key.length(); i ++ )
{
char ch = key.at(i);
if( i%2==0)
res+=(int)ch;
else
res-=(int)ch;
}
return (int)fabsf((float)res) % _SIZE;
}
void HashInsert (string key, int val){
int index= HashFonction(key);
HashEntry s(val, key);
Insert(a[index],s);
}
int HashSearch(string key)
{
int inx=HashFonction(key);
Link *head=a[inx];
if(head==NULL){
return -1;
}
while(head!=NULL){
if(head->data.Name==key)
return head->data.Tel;
head=head->next;
}
return -1;
}
};
After implement this class, i programmed following codes but the result of Search is -1 :-/
HashTable ht;
ht.HashInsert("Hossein", 849348);
ht.HashInsert("Ali", 94343);
ht.HashInsert("Fatemeh", 940343);
cout << ht.HashSearch("Ali") << endl; // output = -1 :-/
Could anyone please explain what is wrong ?
Thanks for your attention
You are passing pointer head to function Insert by value, so array “a” in class Hash table is not altered. Passing by reference fixes the problem: