线性探测法的查找函数
试实现线性探测法的查找函数。
函数接口定义:
1 | Position Find( HashTable H, ElementType Key ); |
其中HashTable
是开放地址散列表,定义如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #define MAXTABLESIZE 100000 /* 允许开辟的最大散列表长度 */ typedef int ElementType; /* 关键词类型用整型 */ typedef int Index; /* 散列地址类型 */ typedef Index Position; /* 数据所在位置与散列地址是同一类型 */ /* 散列单元状态类型,分别对应:有合法元素、空单元、有已删除元素 */ typedef enum { Legitimate, Empty, Deleted } EntryType; typedef struct HashEntry Cell; /* 散列表单元类型 */ struct HashEntry{ ElementType Data; /* 存放元素 */ EntryType Info; /* 单元状态 */ }; typedef struct TblNode *HashTable; /* 散列表类型 */ struct TblNode { /* 散列表结点定义 */ int TableSize; /* 表的最大长度 */ Cell *Cells; /* 存放散列单元数据的数组 */ }; |
函数Find
应根据裁判定义的散列函数Hash( Key, H->TableSize )
从散列表H
中查到Key
的位置并返回。如果Key
不存在,则返回线性探测法找到的第一个空单元的位置;若没有空单元,则返回ERROR
。
裁判测试程序样例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | #include <stdio.h> #define MAXTABLESIZE 100000 /* 允许开辟的最大散列表长度 */ typedef int ElementType; /* 关键词类型用整型 */ typedef int Index; /* 散列地址类型 */ typedef Index Position; /* 数据所在位置与散列地址是同一类型 */ /* 散列单元状态类型,分别对应:有合法元素、空单元、有已删除元素 */ typedef enum { Legitimate, Empty, Deleted } EntryType; typedef struct HashEntry Cell; /* 散列表单元类型 */ struct HashEntry{ ElementType Data; /* 存放元素 */ EntryType Info; /* 单元状态 */ }; typedef struct TblNode *HashTable; /* 散列表类型 */ struct TblNode { /* 散列表结点定义 */ int TableSize; /* 表的最大长度 */ Cell *Cells; /* 存放散列单元数据的数组 */ }; HashTable BuildTable(); /* 裁判实现,细节不表 */ Position Hash( ElementType Key, int TableSize ) { return (Key % TableSize); } #define ERROR -1 Position Find( HashTable H, ElementType Key ); int main() { HashTable H; ElementType Key; Position P; H = BuildTable(); scanf ( "%d" , &Key); P = Find(H, Key); if (P==ERROR) printf ( "ERROR: %d is not found and the table is full.\n" , Key); else if (H->Cells[P].Info == Legitimate) printf ( "%d is at position %d.\n" , Key, P); else printf ( "%d is not found. Position %d is returned.\n" , Key, P); return 0; } /* 你的代码将被嵌在这里 */ |
1 2 3 4 5 6 7 8 9 10 11 12 13 | Position Find( HashTable H, ElementType Key ){ Position p0,p; int Cnum=0; //冲突数 p=p0=Hash(Key,H->TableSize); while (H->Cells[p].Info!=Empty&&H->Cells[p].Data!=Key){ Cnum++; if (Cnum==MAXTABLESIZE){ return ERROR; } p=(p0+Cnum)%H->TableSize; } return p; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统