您的位置:首页 > 其它

链接法hash表

2016-06-26 18:07 225 查看
/*
*一个通过链接法解决碰撞问题的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;
}


运行结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  散列表 链接法