#include<stdio.h>
#include<stdlib.h>
#define NewArray(k) (HashNode*)malloc((k)*sizeof(HashNode))
#define TRUE 1
#define FALSE 0
#define NeverUsed -9999
enum ResultCode {UnderFlow ,OverFlow, Success, Duplicate, NotPresent};
typedef struct hashnode {
int Key;
int Empty;
}HashNode;
typedef struct hashtable {
int M;
HashNode* t;
}HashTable;
void CreateHashTable(HashTable *htb, int divitor) {
int i;
htb->M = divitor;
htb->t = NewArray(htb->M);
for (i = 0; i < htb->M;i++) {
htb->t[i].Empty = TRUE;
htb->t[i].Key = NeverUsed;
}
}
enum ResultCode hSearch(HashTable* htb, int k, int *pos) {
int i, j;
*pos = k % htb->M;
if (*pos<0) {
*pos = htb->M + *pos;
}
i = *pos; j = -1;
do {
if (htb->t[*pos].Key == NeverUsed && j == -1) {
j = *pos;
}
if (htb->t[*pos].Empty) {
break;
}
if (htb->t[*pos].Key==k) {
return Success;
}
*pos = (*pos + 1) % htb->M;
} while (*pos!=i);
if (j==-1) {
return OverFlow;
}
*pos = j;
return NotPresent;
}
void Search(HashTable *htb, int k) {
int*pos = (int*)malloc(sizeof(int));
enum ResultCode result = hSearch(htb, k, pos);
if (result ==Success) {
printf("Find it! The location is: %d\n",*pos);
}
else {
printf("Didn't find it!\n");
}
}
void Insert(HashTable* htb, int x) {
int *pos = (int*)malloc(sizeof(int));
enum ResultCode result = hSearch(htb, x, pos);
if (result ==NotPresent) {
htb->t[*pos].Key = x;
htb->t[*pos].Empty = FALSE;
}
else {
printf("Cannot Insert!\n");
}
}
void Delete(HashTable* htb, int x) {
int* pos = (int*)malloc(sizeof(int));
enum ResultCode result = hSearch(htb, x, pos);
if (result == Success) {
htb->t[*pos].Key =NeverUsed;
htb->t[*pos].Empty =TRUE;
}
else {
printf("Cannot Delete!\n");
}
}
void PrintHashTable(HashTable* htb) {
int i;
for (i = 0; i < htb->M;i++) {
printf("{%d}[%d] ",htb->t[i].Key,htb->t[i].Empty);
}
printf("\n");
}
void main() {
HashTable* htb;
htb = (HashTable*)malloc(sizeof(HashTable));
CreateHashTable(htb, 11);
PrintHashTable(htb);
Insert(htb,99);
PrintHashTable(htb);
Insert(htb, 88);
PrintHashTable(htb);
Insert(htb, 77);
PrintHashTable(htb);
Insert(htb, -2);
PrintHashTable(htb);
Insert(htb, -1);
PrintHashTable(htb);
Search(htb, 100);
Insert(htb, 100);
Insert(htb, 53);
Insert(htb, 23);
PrintHashTable(htb);
Delete(htb, -2);
PrintHashTable(htb);
}
散列表-开地址法-线性探查法
最新推荐文章于 2022-04-04 15:45:59 发布