哈希表集锦

/* 
1、哈希表的地址链表法 


*/


//哈希表的地址链表法
/* 散列表(Hash table,也叫哈希表),是根据关键码值(Key value)而直接进行访问的数据结构。也就是说,
它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。这个映射函数叫做散列函数,
存放记录的数组叫做散列表。 */
//HashTable.h
#include "stdafx.h"
#include "LinkList.h"
#include <stdio.h>
int main()
{
	HashTable H;
	InitHashTable(&H);
	for(int i = 0;i < MAXSIZE * 2;i += 2)
		InsertHashTable(&H,i);
	printf("请输入要查找的内容:\n");
	int key;
	scanf("%d",&key);
	if(SearchHashTable(&H,key))
		printf("在哈希表中找到关键字:%d\n",key);
	else
		printf("在哈希表中未找到关键字:%d\n",key);
	return 0;
}

///
//method.cpp
#include "stdafx.h"
#include "HashTable.h"
#include <stdio.h>
#include <stdlib.h>
void InitHashTable(HashTable *H) //初始化哈希表
{
	H->count = MAXSIZE; //初始化哈希表的大小
	H->table = (Node *)malloc(sizeof(Node) * H->count); //创建哈希表
	for(int i = 0;i < H->count;++i) //初始化哈希表的数据
	{
		H->table[i].data = NULLKEY;
		H->table[i].next = NULL;
	}
}
int Hash(int key)  //哈希表函数
{
	return key % MAXSIZE;
}
void InsertHashTable(HashTable *H,int key) //将关键字key插入哈希表
{
	int addr = Hash(key);
	if(H->table[addr].data != key && H->table[addr].data != NULLKEY) //如果为真,创建单链表
	{
		Node *temp = (Node *)malloc(sizeof(Node));
		temp->next = H->table[addr].next;
		temp->data = key;
		H->table[addr].next = temp;
	}
	else if(H->table[addr].data == NULLKEY)  //则否直接填入
		H->table[addr].data = key;
}
bool SearchHashTable(HashTable *H,int key) //查找关键字key的值
{
	int addr = Hash(key);
	if(H->table[addr].data == key)
		return true;
	Node *p = H->table[addr].next;
	while(p != NULL) //查找单链表
	{
		if(p->data == key)
			return true;
		else
			p = p->next;
	}
	return false;
}

///
//main.cpp
#include "stdafx.h"
#include "HashTable.h"
#include <stdio.h>
int main()
{
	HashTable H;
	InitHashTable(&H);
	for(int i = 0;i < MAXSIZE * 2;i += 2)
		InsertHashTable(&H,i);
	printf("请输入要查找的内容:\n");
	int key;
	scanf("%d",&key);
	if(SearchHashTable(&H,key))
		printf("在哈希表中找到关键字:%d\n",key);
	else
		printf("在哈希表中未找到关键字:%d\n",key);
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值