散列技术之线性探测法

源代码如下:


#include <stdlib.h>
#include <stdio.h>
#define hash(v,M) (v % M)
#define null(A) (key(st[A]) == key(NULLitem)) 
typedef char Key;
struct Item{
	Key key;
};
static struct Item NULLitem ;
static struct Item *st;
static int N , M ;

Key key(Item item){
	return item.key;
}

//初始化 
void STinit(int max){
	int i ;
	N = 0; M = 2 * max;
	st = (Item *)malloc(M*sizeof(Item));
	for(i=0;i<M;i++)st[i] = NULLitem;
}
//节点个数 
int STcount(){
	return N; 
} 

//搜索主程序 
Item STsearch(Key v){
	int i = hash(v,M) ;
	while(!null(i))
		if(v == key(st[i]))return st[i];
		else i = (i+1) & M;
	return NULLitem;
}

//插入主程序 
void STinsert(Item item){
	int i = hash(key(item),M) ;
	printf("%d %d %d\n",key(item),M, i) ;
	while(!null(i)) i = (i+1) & M;
	st[i] = item; N++;
}

//删除主程序
void STdelete(Item item){
	int j, i = hash(key(item),M) ; Item v;
	while(!null(i))
		if(key(item) == key(st[i]))break;
		else i = (i+1) & M;
	st[i] = NULLitem; N--;
	for(j = i+1;!null(j);j=(j+1)%M,N--){
		v = st[j]; st[j] =NULLitem; STinsert(v);
	}
}

void p(){
	struct Item *tmp = st;
	int i ;
	for(i=0;i<M;i++)
		if(!null(i)) printf("%c ",key(st[i]));
	printf("\n");
	
}
main(){
	STinit(13);
	struct Item item[13] ={'a','s','e','r','c','h','i','n','g','x','m','p','l'};
	int i;
	for(i = 0; i<13;i++)
		STinsert(item[i]);
	p();
	printf("search: %c \n",key(STsearch('e')));
	STdelete(item[10]);
	p();
	
	
}


运行结果




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值