1 实验目的:熟练并掌握查找的过程、方法和应用
2 实验内容:
问题描述:
设计一个电话号码查找程序,为来查询人提供电话号码的查询服务。
基本要求:
(1)以你所在的班级为查询范围,假设人名为中国人姓名的汉语拼音形式。人数不能少于10人。
(2)完成根据人名来查找相应的电话号码。
测试数据:
由同学们根据实际情况指定
2 实验内容:
问题描述:
设计一个电话号码查找程序,为来查询人提供电话号码的查询服务。
基本要求:
(1)以你所在的班级为查询范围,假设人名为中国人姓名的汉语拼音形式。人数不能少于10人。
(2)完成根据人名来查找相应的电话号码。
测试数据:
由同学们根据实际情况指定
3 实验要求:任选一种高级程序语言编写源程序,并调试通过,测试正确。
用hash表写的不错,转载了~~
注意一下,那个hash函数~
#include<iostream>
#include<cstring>
using namespace std;
const int MaxSize = 10000;
const int MOD = 9973;
struct User{ // 每个用户的数据结构。
char name[20];
char tel_num[20];
};
struct Node{ // hash表内每个结点的数据结构。
User user;
Node *next;
};
int user_num;
Node *hashtable[MaxSize]; // hash表的表头指针数组。
int ELFhash(char *key){ // hash函数:著名的ELFhash算法。
unsigned long h = 0;
while(*key){
h = (h<<4) + *key++;
unsigned long g = h&0Xf0000000L;
if(g) h ^= g>>24;
h &= ~g;
}
return h % MOD;
}
void add_record(char *name, char *tel_num){ // 添加一个记录。
int key = ELFhash(name);
Node *node = new Node;
strcpy(node->user.name, name);
strcpy(node->user.tel_num, tel_num);
node->next = hashtable[key];
hashtable[key] = node;
}
bool query(char *name, char *tel_num){ // 查询一个记录。
int key = ELFhash(name);
Node *p = hashtable[key];
while(p != NULL){
if(strcmp(name, p->user.name) == 0){
strcpy(tel_num, p->user.tel_num);
return true;
}
p = p->next;
}
return false;
}
int main(){
int i, ope;
char name[20], tel_num[20];
memset(hashtable, 0, sizeof(hashtable));
cout << "系统初始化:先录入用户的人数:";
cin >> user_num;
cout << "请录入他们的名字和电话号码:" << endl;
for(i = 0; i < user_num; i ++){
cin >> name >> tel_num;
add_record(name, tel_num);
}
cout << "系统初始化完毕。" << endl;
while(1){
cout << "\n请输入要执行的操作(1.查询,0.退出系统): ";
cin >> ope;
if(ope != 1) break;
cout << "请出入要查询的用户名: ";
cin >> name;
if(!query(name, tel_num)) cout << "对不起,没有你要查询的用户。" << endl;
else cout << "你所查询用户的电话号码为:" << tel_num << endl;
}
return 0;
}