6-2 線性探測法的查詢函式;
#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;
}
/* 你的程式碼將被嵌在這裡 */
Position Find( HashTable H, ElementType Key ){
int p=Key%H->TableSize,cnt=0;
while((H->Cells)[p].Data!=-1&&(H->Cells)[p].Data!=Key&&cnt<=H->TableSize){
p++;
cnt++;
if(p==H->TableSize){
p=0;
}
}
if(cnt>H->TableSize){
return ERROR;
}
else return p;
}