散列表-开地址法-线性探查法

#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);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值