作者:@kuaiquxie
作者的github:https://github.com/bitebita
本文为作者原创,如需转载,请注明出处:https://www.cnblogs.com/dzwj/p/15659510.html
线性探测法的查找函数
试实现线性探测法的查找函数。
函数接口定义:
| Position Find( HashTable H, ElementType Key ); |
其中HashTable
是开放地址散列表,定义如下:
| #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
。
裁判测试程序样例:
| #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:(注:-1表示该位置为空。下同。)
| 11 |
| 11 88 21 -1 -1 5 16 7 6 38 10 |
| 38 |
输出样例1:
输入样例2:
| 11 |
| 11 88 21 -1 -1 5 16 7 6 38 10 |
| 41 |
输出样例2:
| 41 is not found. Position 3 is returned. |
输入样例3:
| 11 |
| 11 88 21 3 14 5 16 7 6 38 10 |
| 41 |
输出样例3:
| ERROR: 41 is not found and the table is full. |
| |
| |
| 代码如下: |
Position Find( HashTable H, ElementType Key ){
int x=Hash(Key,H->TableSize);
int a=0;
while(a<H->TableSize){
if( H->Cells[x].Info==Empty//题目里还给了个Deleted,没有测试点不鸟它了
||H->Cells[x].Data == Key){//可不能等于Legitimate
return x;
}
x=(x+1)%H->TableSize;
a++;
}
return ERROR;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」