[数据结构]Hash表初学(数组链表)

本文详细介绍了哈希表的基本概念,通过数组实现链表,利用模运算进行哈希函数设计,并展示了添加、查找等操作的实现过程。
/*
Name:Hash表初学 (数组实现链表 h(x) = x mod n )

Actor:HT

Time:2015年9月27日

Error Reporte:	1.add函数 来龙去脉理解清楚

*/

#include"stdio.h"
#include"string.h"
#include"stdlib.h"


int hash[9];		//9位表

int link[10000];	//单个数组构成的N个链表,下标、数值都是序号 简直黑科技
int value[10000];	//下标序号,数值就是真值
int rear;			//最后的一个序号,用来安排空的地方

int fhash(int x)	//hash函数
{
	return x % 9;
}

void add(int x)		//添加
{
	int temp = hash[fhash(x)];
	while (temp != 0)
	{
		if (value[link[temp]] == x) return;
		temp = link[temp];
	}
	value[rear] = x;
	link[rear] = hash[fhash(x)];	//连接到原队首
	hash[fhash(x)] = rear;			//自己成为队首
	rear++;
}

void serach(int x)//查找
{
	int temp = hash[fhash(x)];
	while (temp != 0)
	{
		if (value[link[temp]] == x)
		{
			printf("此值存在\n");
			return;
		}
		temp = link[temp];
	}
	printf("查无此值\n");
}

void vis()
{
	int i;
	int temp;
	for (i = 0; i < 9; i++)
	{
		printf("第%d个hash槽:	",i);
		temp = hash[i];
		if (hash[i] == 0)
		{
			printf("Empty\n");
			continue;
		}
		while (temp != 0)
		{
			printf("%d	", value[temp]);
			temp = link[temp];
		}
		printf("\n");
	}
}

void del(int x)//删除
{
	;//暂不用数组实现,没有意义... ...用链表就easy多了
}

int main()
{
	memset(hash, 0, sizeof(hash));
	memset(link, 0, sizeof(link));
	rear = 1;
	for (int i = 1; i < 5; i++)
	{
		add(i);
	}
	vis();

	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值