/*
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;
}
[数据结构]Hash表初学(数组链表)
最新推荐文章于 2024-10-08 14:22:32 发布
