2、编写程序,新建一个容量不小于100的哈希表(采用线性探测法解决冲突),随机生成50个整数插入哈希表中,整数范围在[0,100]之间。从键盘输入一个整数,在哈希表中查找,若找到,输出下标,否则输出“

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
enum EntryType {Legitimate, Empty, Deleted};
struct HashEntry{
    int Data;
    enum  EntryType Info;
};
struct HashTable{
    int TableSize;
    struct HashEntry * Cells; /* 存放条目的数组 */
};
struct HashTable *CreateTable() {
    struct HashTable *H;
    int i;
    H =(struct HashTable*)malloc(sizeof(struct HashTable));
    H->TableSize =101; /* 得到素数作为表大小 */
    H->Cells =(struct HashEntry*)malloc(sizeof(struct HashEntry) * H->TableSize);
    for (i = 0; i < H->TableSize; i ++)
        H->Cells[i].Info = Empty;

    return H;
}
int Hash(int K, int TableSize) {
    int sum = 0;
    return sum % TableSize;
}
int Find(struct HashTable *H, int K) {
    int Pos, NewPos;
    int CNum = 0;

    Pos = Hash(K, H->TableSize);
    NewPos = Pos;
    while (H->Cells[NewPos].Info != Empty 
           && H->Cells[NewPos].Data != K ) {
        CNum ++;
        NewPos = Pos + CNum;
        if (NewPos >= H->TableSize)
            NewPos %= H->TableSize;
    }
    return NewPos;
}
int FindX(struct HashTable *H, int K) {
    int Pos, NewPos;
    int CNum = 0;

    Pos = Hash(K, H->TableSize);
    NewPos = Pos;
    while (H->Cells[NewPos].Info != Empty 
           && H->Cells[NewPos].Data != K ) {
        CNum ++;
        NewPos = Pos + CNum;
        if (NewPos >= H->TableSize)
            NewPos %= H->TableSize;
    }
    if( H->Cells[NewPos].Data == K){
    	printf("%d\n",NewPos);
    	
	}else{
		printf("not found");
	}
}
void Insert(struct HashTable *H, int y) {
    int Pos;

    Pos = Find(H, y);
    if (H->Cells[Pos].Info != Legitimate) {
        H->Cells[Pos].Info = Legitimate;
        H->Cells[Pos].Data = y;
    }
}

int main(){
	int i,j;
	struct HashTable *H;
	H=CreateTable();
	srand((int)time(NULL));
	for(i=0;i<100;i++){
		Insert(H,rand()%101);
	}
	int x;
	scanf("%d",&x);
	FindX(H,x);
	return 0;
} 
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值