数据结构学习第二十四课(hush表)

hash表:

1 hash三要素:
a,数据的范围:数据表示
b,合适的hash函数:如科学计数法
c,冲突的解决

1 源文件

#include<stdio.h>
#include<iostream>
using namespace std;
//保存数据的节点
struct Node
{
	struct Node* pNext;
	int data;
};
//一个数据:struct Node*
struct Hash_table
{
	struct Node*** arr[10];
	//vector<vector<vector<Node*>>> arr;

};
struct Node* createNode(int data);
struct Hash_table* createHash();
void initHash(struct Hash_table* hash);
void insertHash(struct Hash_table* hash, int data);
Node* findHash(struct Hash_table* hash, int data);
int main()
{
	struct Hash_table* hash = createHash();
	initHash(hash);
	int a[10];
	for (int i = 0; i < 10; i++)
	{
		a[i] = rand() % 100;
		insertHash(hash, a[i]);
	}
	int n;
	Node* p;
	while (1)
	{
		scanf("%d", &n);
		if (666 == n)break;
		p = findHash(hash, n);
		if (NULL == p)printf("wu\n");
		else printf("is %d\n", p->data);
	}
	return 0;
}
//创建节点
struct Node* createNode(int data)
{
	struct Node* pNew = new Node;
	pNew->data = data;
	pNew->pNext = NULL;
	return pNew;
}
//创建哈希表
struct Hash_table* createHash()
{
	struct Hash_table* pHash = new Hash_table;	
	return pHash;
}
//初始化哈希表
void initHash(struct Hash_table* hash)
{
	memset(hash->arr, NULL, 4 * 10);
}
//插入数据到hash表中
void insertHash(Hash_table* hash, int data)
{
	int ge, shi, bai;
	ge = data % 10;
	shi = data / 10 % 10;
	bai = data / 100 % 10;
	struct Node* temp;
	if (hash->arr[ge] == NULL)
	{
		hash->arr[ge] = new Node * *[10];
		memset(hash->arr[ge], 0, 4 * 10);

		hash->arr[ge][shi] = new Node *[10];
		memset(hash->arr[ge][shi], 0, 4 * 10);
	
		hash->arr[ge][shi][bai] = createNode(data);
	}
	else 
	{
		if (NULL == hash->arr[ge][shi])
		{
			hash->arr[ge][shi] = new Node * [10];
			memset(hash->arr[ge][shi], 0, 4 * 10);

			hash->arr[ge][shi][bai] = createNode(data);
		}
		else 
		{
			if (NULL == hash->arr[ge][shi][bai])
			{
				hash->arr[ge][shi][bai] = createNode(data);

			}
			else
			{
				//冲突 插入到链表末尾
				//定位末尾
				temp = hash->arr[ge][shi][bai];
				while (temp->pNext)
				{
					temp = temp->pNext;
				}
				//添加到末尾节点之后
				temp->pNext = createNode(data);
			}
		}
		

	}
}
//从hash表中找到数据并返回数据地址
Node*  findHash(Hash_table* hash, int data)
{
	int ge, shi, bai;
	ge = data % 10;
	shi = data / 10 % 10;
	bai = data / 100 % 10;
	struct Node* temp = NULL;
	if (NULL == hash)return NULL;
	if (NULL == hash->arr[ge])return NULL;
	if (NULL == hash->arr[ge][shi])return NULL;
	if (NULL == hash->arr[ge][shi][bai])return NULL;
	
	temp = hash->arr[ge][shi][bai];
	while (temp)
	{
		if (temp->data == data)
			return temp;
		temp = temp->pNext;
	}
	return NULL;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值