例7.2连地址法(除留余数法和链地址法构造散列表)

除留余数法和链地址法构造散列表

在这里插入图片描述

实现

#pragma once
#include <iostream>
using namespace std;
#define LEN 13

typedef struct hash_node 
{
	int data;
	struct hash_node* next;
}hash_node;


//表里存的是个地址,这是个HashNode*类型的数组
typedef hash_node* HashTable[LEN];


//初始化
void InitHashTable(HashTable& ht) 
{
	for (int i = 0; i < LEN; i++) 
	{
		ht[i] = NULL;
	}
}

//散列函数
int Hash(int key)
{
	return key % LEN;
}


//插入
void InsertHashTable(HashTable& ht,int key)
{
	int index = Hash(key);
	hash_node* s = new hash_node;
	s->data = key;
	if (ht[index] == NULL)
	{
		//数组里存的是原来结点的地址
		s->next = ht[index];
		ht[index] = s;
	}
	else
	{
		//插入该结点
		hash_node* temp = ht[index];
		while (temp->next != NULL)
		{
			temp = temp->next;
		}
		//插入该结点
		s->next = temp->next;
		temp->next = s;
	}
}

//打印输出
void ShowHashTable(HashTable& ht) 
{
	for (int i = 0; i < LEN; i++) 
	{
		cout << i <<": ";
		hash_node* p = ht[i];
		while (p != NULL)
		{
			printf("%d-->", p->data);
			p = p->next;
		}
		cout << endl;
	}
}

int main()
{

	HashTable ht;
	InitHashTable(ht);

	/*InsertHashTable(ht,11);
	InsertHashTable(ht, 14);
	InsertHashTable(ht, 1);

	cout << ht[11 % 13]->data << endl;
	cout << ht[14 % 13]->data << endl;
	cout << ht[14 % 13]->next->data << endl;*/

	int array[] = { 19,14,23,1,68,20,84,27,55,11,10,79 };
	for (int i = 0; i < sizeof(array) / sizeof(int); i++)
	{
		InsertHashTable(ht, array[i]);
	}

	cout << "散列表为:" << endl;
	ShowHashTable(ht);
	
	system("pause");
	return 0;
}

运行结果

在这里插入图片描述

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值