l拉链法

//拉链法(利用链表)解决哈希冲突问题
#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;                        //将结点加入链表
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值