#include <stdio.h>
#include <windows.h>
# define M 10
typedef struct hash{
int *elem;
}HashTable;
void Init(HashTable * H);
void Insert(HashTable * H, int key);
bool Search(HashTable * H, int key, int *addr);
void Destory(HashTable * H);
void Print(HashTable H);
int Hash(int key);
int main(){
HashTable H;
Init(&H);
Insert(&H, 1);
Insert(&H, 2);
Insert(&H, 3);
Print(H);
int addr;
if(Search(&H, 5, &addr))
printf("%d\n", addr);
else
printf("NoFind!\n");
Destory(&H);
Print(H);
system("pause");
return 0;
}
int Hash(int key){
return key % M;
}
void Init(HashTable * H){
if(NULL == H)
return;
H->elem = (int*)malloc(M*sizeof(int));
if(!H->elem)
exit(-1);
for(int i = 0; i < M; i++)
H->elem[i] = -1;
}
void Insert(HashTable * H, int key)
{
if(NULL == H)
return;
int addr = Hash(key);
while(H->elem[addr] != -1)
addr = (addr+1)%M;
H->elem[addr] = key;
}
bool Search(HashTable * H, int key, int *addr)
{
if(NULL == H)
return -1;
*addr = Hash(key);
while(H->elem[*addr] != key){
*addr = (*addr+1)%M;
if(H->elem[*addr] == -1 || *addr == Hash(key))
return false;
}
return true;
}
void Destory(HashTable * H){
if(NULL == H->elem)
return;
free(H->elem);
H->elem = NULL;
}
void Print(HashTable H){
for(int i = 0; i < M; i++)
printf("%d ", H.elem[i]);
printf("\n");
}
C语言数据结构学习笔记(24)-哈希表开放定址法
最新推荐文章于 2024-07-20 11:22:21 发布