您的位置:首页 > 其它

Hash表

2015-08-26 12:43 267 查看
#include <iostream>
#include <string.h>
using namespace std;

const int NAME_NO = 20;
const int TABLE_SIZE = 50;

typedef struct
{
char *py;
int sum;
}Name;

typedef struct
{
char *py;
int sum;
int si;
}Hash;

Name NameList[NAME_NO];
Hash HashList[TABLE_SIZE];

void init_name_table()
{
NameList[0].py = "zhoujielun";
NameList[1].py = "naying";
NameList[2].py = "halin";
NameList[3].py = "wangfeng";
NameList[4].py = "fenghanzao";
NameList[5].py = "fuzongkai";
NameList[6].py = "hujinbin";
NameList[7].py = "huangjiangwu";
NameList[8].py = "lilongqiang";
NameList[9].py = "guoxiaodong";
NameList[10].py = "liuqing";
NameList[11].py = "zhongqiang";
NameList[12].py = "shenglong";
NameList[13].py = "chulingling";
NameList[14].py = "chengpeisi";
NameList[15].py = "liaoxiaobin";
NameList[16].py = "fenggong";
NameList[17].py = "shunzi";
NameList[18].py = "shihui";
NameList[19].py = "lixiaolong";
NameList[20].py = "zhouxingxing";

for (int i=0; i<NAME_NO; i++)
{
int sum = 0;
for (int j=0; j<strlen(NameList[i].py); j++)
{
sum += *(NameList[i].py+j);
}
NameList[i].sum = sum;
}
}

void create_hash_table()
{
memset(HashList, 0, sizeof(HashList));
for (int i=0; i<NAME_NO; i++)
{
int index = NameList[i].sum%50;

if (HashList[index].si == 0)
{
HashList[index].py = NameList[i].py;
HashList[index].sum = NameList[i].sum;
HashList[index].si = 1;
}
else
{
int count = 1;
do
{
index = (index + NameList[i].sum%10+1)%50;
count++;
}while(HashList[index].si != 0);
HashList[index].py = NameList[i].py;
HashList[index].sum = NameList[i].sum;
HashList[index].si = count;
}
}
}

void print_hash_table()
{
cout << "No     " << "Name     "<<"Si    " << endl;
for(int i=0; i<TABLE_SIZE; i++)
{
cout << i << "     " << (HashList[i].py==NULL?"0":HashList[i].py) << "    " << HashList[i].si << endl;
}
}

void find_name(const char *name)
{
if (NULL == name)
return;

int sum = 0;
for(int i=0; i<strlen(name); i++)
sum += *(name+i);
int index = sum%50;
if (HashList[index].si == 1)
{
cout << "find: " << HashList[index].py << "in index: " << index << "si: " << HashList[index].si << endl;
}
else if (HashList[index].si == 0)
{
cout << "not found: " << name << "in hash table" << endl;
}
else
{
int count = 1;
do
{
index = (index + sum%10+1)%50;
count++;

}while((HashList[index].si==count) || (count > 1000));
cout << "find: " << HashList[index].py << "in index: " << index << "si: " << HashList[index].si << endl;
}
return;
}

int main()
{
init_name_table();
create_hash_table();
print_hash_table();

string name;
cout << "input the name you want find: ";
while(cin>>name)
{
find_name(name.c_str());
cout << "input the name you want find: ";
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: