链接法hash表

来源:互联网 发布:js a href click 编辑:程序博客网 时间:2024/06/09 18:37
/* *一个通过链接法解决碰撞问题的Hash表 *主要实现的功能是: *1.读取全域数据并通过hash映射保存到hash表中 *2.查询一个属于全域中的数据在hash表中的位置 * *          Author: StoryMonster *Last Change Date: 2016/6/24 */#include <iostream>#include <stdlib.h>typedef struct HashTable{    int value;    struct HashTable *next;} HashTable;HashTable *hashTable[10] = {0};/* *返回value在哈希表中的下标 */int CalcHashTableIndex(int value){    return value%10;}/* *将关键字value存入hash表中 */void PutToHashTable(int value){    int index = CalcHashTableIndex(value);    HashTable *p = (HashTable *)malloc(sizeof(HashTable));    p->next = NULL;    p->value = value;    if(hashTable[index] == NULL)    {        hashTable[index] = p;        return ;    }    p->next = hashTable[index]->next;    hashTable[index]->next = p;}void ShowHashTable(){    int i=0;    for(i=0;i<10;i++)    {        HashTable *p = hashTable[i];        std::cout << i <<":";        while(p!=NULL)        {            std::cout << p->value << "  ";            p = p->next;        }        std::cout << std::endl;    }}int main(){    int choice = 0;    int value = 0;    while(1)    {        std::cout << "1:input a value  2:scan hash table" << std::endl;        std::cout << "your choice:";        std::cin >> choice;        switch(choice)        {            case 1: std::cout << "input value:";                    std::cin >> value;                    PutToHashTable(value);                    break;            case 2: ShowHashTable();                    break;        }    }    return 0;}

运行结果
这里写图片描述

0 0
原创粉丝点击