#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 12
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define NULLKEY -32768
//散列表存储结构
typedef int Status;
typedef struct
{
int *elem;
int count;
}HashTable;
int m = 0;
//初始化散列表
Status InitHashTable(HashTable *HT)
{
m = MAXSIZE;
HT->elem = (int *)malloc(sizeof(int)*MAXSIZE);
HT->count = m;
for(int i=0;i<HT->count;i++)
HT->elem[i]=NULLKEY;
return OK;
}
//散列函数
int Hash(int key)
{
return key % m; //除留余法
}
//插入关键字进散列表
void InsertHash(HashTable *HT,int key)
{
int addr = Hash(key);
while(HT->elem[addr] != NULLKEY)
addr = (addr + 1)%m;
HT->elem[addr]=key;
}
//查找
Status SearchHash(HashTable *HT,int key,int *addr) //addr指针记录数值位置
{
*addr = Hash(key);
while(HT->elem[*addr] != key)
{
*addr = (*addr + 1)%m;
if(HT->elem[*addr] == NULLKEY || *addr == Hash(key)) return ERROR; //空值或循环回到原地
}
return OK;
}
int main()
{
HashTable HT;
InitHashTable(&HT);
int arr[] = {12,25,94,45,36,17,30};
for(int i=0;i<7;i++)
InsertHash(&HT,arr[i]);
int addr;
if(SearchHash(&HT,30,&addr)) printf("找到成功,其散列表地址是%d",addr);
else printf("不在散列表里~");
return 0;
}
【数据结构-查找】C语言实现散列表的简单查找
最新推荐文章于 2022-07-10 16:12:26 发布