當前位置:成語大全網 - 新華字典 - 用C編程 設計壹哈希表

用C編程 設計壹哈希表

以下是我用C++編的壹個程序,僅供參考!

#include<iostream>

#include<string>

using namespace std;

#define M 47 //隨機數

#define n 50 //哈希表長

#define q 30 //人數

struct name{

char *py;

int k;

};

name NameList[n];

struct hash{

char *py;

int k;

int si;

};

hash hashlist[n];

void listname()

{

char *f;

int s0,r,i;

NameList[0].py="baojie";

NameList[1].py="chengaoyang";

NameList[2].py="chenguangzhong";

NameList[3].py="chenliangliang";

NameList[4].py="chenyongzhou";

NameList[5].py="fengchao";

NameList[6].py="gexiangfeng";

NameList[7].py="huting";

NameList[8].py="huangpinjin";

NameList[9].py="jiangxiaojia";

NameList[10].py="laidongjie";

NameList[11].py="liyexiao";

NameList[12].py="lidaohui";

NameList[13].py="lijue";

NameList[14].py="lizhuoqun";

NameList[15].py="linfujun";

NameList[16].py="luobin";

NameList[17].py="luokeqing";

NameList[18].py="nichao";

NameList[19].py="panhuafeng";

NameList[20].py="sijun";

NameList[21].py="songzhanhui";

NameList[22].py="sunzhengqing";

NameList[23].py="wanghaofeng";

NameList[24].py="wangjunshuai";

NameList[25].py="wangqinde";

NameList[26].py="wangzejun";

NameList[27].py="wangkeke";

NameList[28].py="weixing";

NameList[29].py="wurenke";

for(i=0;i<q;i++)

{

s0=0;

f=NameList[i].py;

for(r=0;*(f+r)!='\0';r++)

s0+=*(f+r);

NameList[i].k=s0;

}

}

void creathash()

{

int i;

for(i=0;i<n;i++)

{

hashlist[i].py="";

hashlist[i].k=0;

hashlist[i].si=0;

}

for(i=0;i<M;i++)

{

int sum=0;

int adr=(NameList[i].k)%M;

int d=adr;

if(hashlist[adr].si==0)

{

hashlist[adr].k=NameList[i].k;

hashlist[adr].py=NameList[i].py;

hashlist[adr].si=1;

}

else

{

while(hashlist[d].k!=0)

{

d=(d+NameList[i].k%10+1)%M;

sum=sum+1;

}

hashlist[d].k=NameList[i].k;

hashlist[d].py=NameList[i].py;

hashlist[d].si=sum+1;

}

}

}

void findlist()

{

string nam;

int s0=0,r,sum=1;

cout<<"請輸入姓名的拼音:"<<endl;

cin>>nam;

for(r=0;r<20;r++)

s0+=nam[r];

int adr=s0%M;

int d=adr;

if(hashlist[adr].k==s0)

cout<<"姓名:"<<hashlist[adr].py<<" "<<"關鍵字:"<<s0<<" "<<"查找長度為:1"<<endl;

else if(hashlist[adr].k==0)

cout<<"無此記錄!"<<endl;

else

{

int g=0;

while(g==0)

{

d=(d+s0%10+1)%M;

sum=sum+1;

if(hashlist[d].k==0)

{cout<<"無此記錄!"<<endl;

g=1;

}

if(hashlist[d].k==s0)

{

cout<<"姓名:"<<hashlist[adr].py<<" "<<"關鍵字:"<<s0<<" "<<"查找長度為:1"<<endl;

g=1;

}

}

}

}

void display()

{

int i;

for(i=0;i<30;i++)

cout<<NameList[i].py<<" "<<NameList[i].k<<endl;

}

int main()

{

char x;

listname();

creathash();

cout<<"d. 顯示哈希表 f.查找 任意鍵退出 請選擇"<<endl;

while(cin>>x)

{

if(x=='d'){display();cout<<endl;}

else if(x=='f'){findlist();cout<<endl;}

else break;

}

return 0;

}