#include "iostream.h"
#include "fstream.h"
#include "string.h"
#define MaxLen 13
#define Div 11//被除数
typedef struct node
{
char name[20];
int age;
bool tag;
}addrBook;
addrBook *bk=new addrBook[MaxLen];
addrBook *hashbk=new addrBook[MaxLen];//
void ReadFile(int &n)
{
ifstream infile("d:\\list.txt");
n=0;
while (!infile.eof())
{
infile>>bk[n].name;
infile>>bk[n].age;
n++;
}
}
void DispList(int n)
{
for (int i=0;i<n;i++)
cout<<bk[i].name<<'\t'<<bk[i].age<<endl;
}
int HashFunc(int age)//返回age对应的hash函数值
{
int pos=age%Div;
while(hashbk[pos].tag==1)
pos=(pos+1)%Div;
if (hashbk[pos].tag==0)
return pos;
else
return -1;
}
void FillHashTable(int n)
{
int k;//keep the age
int pos;
for (int i=0;i<n;i++)
{
k=bk[i].age;
pos=HashFunc(k);
if(pos!=-1)
{
hashbk[pos]=bk[i];
hashbk[pos].tag=1;
}
else
cout<<"Table Full!"<<endl;
}
}
int SearchHashTable(int age)
{
int pos;
pos=age%Div;
while(hashbk[pos].tag==1&&hashbk[pos].age!=age)
pos=(pos+1)%Div;
if (hashbk[pos].tag==1&&hashbk[pos].age==age)
return pos;
else
return -1;
}
void main()
{
int n;
ReadFile(n);
DispList(n);
for (int i=0;i<MaxLen;i++)
hashbk[i].tag=0;//哈希表中没有此元素
FillHashTable(n);
int res;
res=SearchHashTable(36);
if(res!=-1)
cout<<"the result is :\n"<<hashbk[res].name<<'\t'<<hashbk[res].age<<endl;
}