#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;
}
2、编写程序,新建一个容量不小于100的哈希表(采用线性探测法解决冲突),随机生成50个整数插入哈希表中,整数范围在[0,100]之间。从键盘输入一个整数,在哈希表中查找,若找到,输出下标,否则输出“
最新推荐文章于 2022-09-13 13:55:30 发布