//拉链法(利用链表)解决哈希冲突问题
#include <iostream>
#include <ctime>
#define INDEXBOX 7 //哈希表的元素个数
#define MAXNUM 13 //数据个数
using namespace std;
void CreatTable(int); //声明建立哈希表子程序
void PrintData(int); //声明输出哈希表子程序
class list //声明链表结构
{
public:
int nval;
class list *next;
};
list IndexTable[INDEXBOX]; //声明哈希表阵列
void main()
{
int i, nData[MAXNUM];
srand((unsigned)time(NULL));
//初始化哈希表
for(i = 0; i < INDEXBOX; i++)
{
IndexTable[i].nval = -1;
IndexTable[i].next = NULL;
}
//构造原始数据
cout << "原始数据:\n";
for(i = 0; i < MAXNUM; i++)
{
nData[i] = rand()%30 + 1;
cout << nData[i] << "\t";
}
//建立并输出哈希表
cout << "\n哈希表\n";
for(i = 0; i < MAXNUM; i++) //对于每一个数据元素都加到哈希表里
CreatTable(nData[i]); //建立哈希表
for(i = 0; i < INDEXBOX; i++) //输出哈希表
PrintData(i);
cout << endl;
}
void PrintData(int nval) //输出哈希表子程序
{
list *head;
int i = 0;
head = IndexTable[nval].next; //起始指针
cout << " " << nval << "\t" ;
while(head != NULL)
{
cout << " " << head->nval << "--";
head = head->next;
}
cout << endl;
}
void CreatTable(int val) //建立哈希表子程序
{
list *newnode;
list *current;
int nHash;
nHash = val % 7; //哈希函数除以7取余数
newnode = new list;
current = new list;
newnode->nval = val;
newnode->next = NULL;
*current = IndexTable[nHash];
if(current->next == NULL)
IndexTable[nHash].next = newnode;
else
while(current->next != NULL)
current = current->next;
current->next = newnode; //将结点加入链表
}