#include<stdio.h>
#include<stdlib.h>
#define NUM 5
typedef struct HashList
{
int num;
char* data;
}HashList;
HashList* initList()
{
HashList* list = (HashList*)malloc(sizeof(HashList));
list->num = 0;
list->data = (char*)malloc(sizeof(char) * NUM);
for (int i = 0; i < NUM; i++)
{
list->data[i] = 0;
}
return list;
}
int hash(int data)//计算hash值
{
return data % NUM;
}
void put(HashList* list, char data)//往hash存
{
int index = hash(data);
if (list->data[index] != 0)//如果有值
{
int count = 1;
while (list->data[index] != 0)//如果还有值那就进行线性探测法
{
index = hash(hash(data) + count);
count++;
}
}
//无值就直接存储
list->data[index] = data;
}
int main()
{
HashList* list = initList();
put(list, 'A');
put(list, 'F');
printf("%c\n", list->data[0]);
printf("%c\n", list->data[1]);
return 0;
}
C语言哈希表的线性探测法
最新推荐文章于 2022-11-09 14:22:05 发布