您的位置:首页 > 理论基础 > 数据结构算法

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

2015-09-27 11:31 543 查看
/*
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: