线性探测法的查找函数

本文深入探讨了散列表查找算法的实现,通过一个详细的裁判测试程序样例,讲解了如何在散列表中寻找特定元素的过程。包括散列表的构建、散列函数的设计以及冲突解决策略。适用于对数据结构和算法有兴趣的读者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

裁判测试程序样例:

#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 Position Find( HashTable H, ElementType Key )
 2 {
 3     int HashPos = Hash(Key, H->TableSize);
 4     int Pre;   //Pre表示初始时HashPos的前一个位置
 5     (HashPos-1 >= 0) ? (Pre = HashPos-1) : (Pre = (HashPos-1)+H->TableSize);
 6     
 7     /* 是空位或者遍历完哈希表中的数组时,跳出循环 */
 8     for(; H->Cells[HashPos].Info != Empty && HashPos != Pre; HashPos = (HashPos+1)%H->TableSize)
 9         if(H->Cells[HashPos].Data == Key && H->Cells[HashPos].Info == Legitimate)
10             return HashPos;
11             
12     if(H->Cells[HashPos].Info == Empty)  /* 如果此时的位置是一个空位 */
13         return HashPos;
14     else        /* 非空位,把数组遍历完了 */
15         return ERROR;
16 }

 

转载于:https://www.cnblogs.com/FengZeng666/p/9825581.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值