ELFhash 实现 (转)

 http://blog.sina.com.cn/s/blog_6635898a0100npzt.html

1 实验目的:熟练并掌握查找的过程、方法和应用

2 实验内容:

问题描述:

  设计一个电话号码查找程序,为来查询人提供电话号码的查询服务。

基本要求:

 (1)以你所在的班级为查询范围,假设人名为中国人姓名的汉语拼音形式。人数不能少于10人。

 (2)完成根据人名来查找相应的电话号码。

测试数据:

   由同学们根据实际情况指定

3 实验要求:任选一种高级程序语言编写源程序,并调试通过,测试正确。

 

源代码:

#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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值