#include <stdio.h>
#include <stdlib.h>
#define HASHSIZE 12
#define NULLKEY -32768
#define SUCESS 1
#define FAILED 0
/*哈希表定义*/
typedef struct
{
int *elem;
int count;
}HasHTable;
int m = 0;//散列表表长
/*哈希表初始化*/
void HashInit (HasHTable *H)
{
int i;
m = HASHSIZE;
H->count = m;
H->elem = (int *)malloc(m*sizeof(int));
for(i = 0; i < H->count; i++)
{
H->elem[i] = NULLKEY;
}
}
/*哈希表插入*/
void InsertHash (HasHTable *H, int key)
{
int addr;
addr = key%m;//除留取余法
while(H->elem[addr] != NULLKEY)
{
addr = (addr+1)%12;
}
H->elem[addr] = key;
}
/*哈希表查找*/
int HashSearch (HasHTable *H, int key)
{
int addr;
addr = key%m;
while(H->elem[addr] != key)
{
addr = (addr+1)%m;
if(H->elem[addr] == NULLKEY || addr == key%m)
{
return FAILED;
}
}
return SUCESS;
}
/*哈希表创建*/
void CreatHash (HasHTable *H, int *key)
{
for(int i = 0; i < 12; i++)
{
InsertHash(H, key[i]);
}
}
int main ()
{
HasHTable H;
int table[12] = {12, 67, 56, 16, 25, 37, 22, 29, 15, 47, 48, 34};
HashInit(&H);
CreatHash(&H, table);
for(int i = 0; i < 12; i++)
{
printf("%d ", i);
}
printf("\n");
for(int i = 0; i < 12; i++)
{
printf("%d ", H.elem[i]);
}
printf("%d\n", HashSearch (&H, 24));
return 0;
}
哈希表操作
最新推荐文章于 2020-12-13 11:11:31 发布