#include<iostream>
#include<string.h>
#define N 20
using namespace std;
struct Node//标记学生信息的结构体
{
char name[20];
char num[10];
char address[20];
};
Node data[N];
int Hash(const char str[])//除留余数法的hash函数
{
int i=0;
int key=0;
while(str[i]!=NULL)
{
key+=(int)str[i];
i++;
}
key=key%19;
return key;
}
void Hashname(int usign[], int *K, char name[],char num[],char address[])
{//以名字为关键值输入哈希表
int key;
int j;
key=Hash(name);
if(usign[key]==1)
{
for(j=1;j<N;j++)//以线性探测再散列的方式处理冲突
{
key=(key+j)%N;
if(usign[key]==0)
break;
}
}
usign[key]=1;
strcpy(data[key].name,name);
strcpy(data[key].num,num);
strcpy(data[key].address,address);
(*K)++;
}
int Searchname(const int KKK,const int usign[],const char uname[])//查找给定名字的数组下表
{
int key;
int j;
int a=1;
key=Hash(uname);
if(usign[key]==0)
{
cout<<"无记录"<<endl;
return(-1);
}
else if((usign[key]==1)&&strcmp(data[key].name,uname)!=0)
{
for(j=1;j<N,a<KKK;j++)
{
key=(key+j)%N;//线性探测再散列处理冲突
a++;
if((usign[key]==1)&&strcmp(data[key].name,uname)==0)
{
return key;
}
}
if(a>=KKK) return(-1);
}
else if((usign[key]==1)&&strcmp(data[key].name,uname)==0)
return key;
}
void Outname(int uK,int usign[])//输出指定下表的元素
{
if((uK<0)||(usign[uK]==0))
{
cout<<"无记录"<<endl;
return;
}
cout<<"姓名:"<<data[uK].name<<endl;
cout<<"学号:"<<data[uK].num<<endl;
cout<<"地址:"<<data[uK].address<<endl;
}
void Outlist()//输出整个哈希表
{
int i;
for(i=0;i<N;i++)
{
cout<<"姓名:"<<data[i].name<<endl;
cout<<"学号:"<<data[i].num<<endl;
cout<<"地址:"<<data[i].address<<endl;
cout<<"******************************"<<endl;
}
}
void main()
{
int sign[N];
int l;
int n;
for(l=0;l<N;l++)
sign[l]=0;
for(l=0; l<N; l++)
{
strcpy(data[l].address,"");
strcpy(data[l].name,"");
strcpy(data[l].num,"");
}
Node mdata;
int knumber=0;//记录元素的个数
cout<<"\t\t____________________"<<endl;
cout<<"\t\t*1 输入记录"<<endl;
cout<<"\t\t*2 按姓名查找并显示记录"<<endl;
cout<<"\t\t*3 显示全部记录"<<endl;
cout<<"\t\t*4 退出"<<endl;
cout<<"\t\t____________________"<<endl;
while(1)
{
cout<<"请输入1-4:"<<endl;
cin>>n;
switch(n)
{
case 1: int m;
cout<<"请输入需要输入的记录条数:(不超过20)"<<endl;
cin>>m;
for(l=0;l<m;l++)
{
cout<<"请输入第"<<l+1<<"条记录:"<<endl;
cout<<"姓名:";
cin>>mdata.name;
cout<<"学号:";
cin>>mdata.num;
cout<<"地址:";
cin>>mdata.address;
Hashname(sign,&knumber,mdata.name,mdata.num,mdata.address);
}
break;
case 2: char mname[10];
int mkey;
cout<<"请输入姓名:"<<endl;
cin>>mname;
mkey=Searchname(knumber,sign,mname);
Outname(mkey,sign);
break;
case 3: Outlist();
break;
case 4: exit(0);
}
}
}