#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXS 8 //字符串长度
#define MAXD 3 //参与散列映射的字符个数
#define MAXB 5//每个字符占得位数
#define MASK (1<<(MAXD*MAXB))-1
struct node{
char data[MAXS+1];
int flag;
};
struct hash{
int size;
struct node *cell;
};
typedef struct hash *HashTable;
HashTable Initial(int P)
{
HashTable H;
H=malloc(sizeof(struct hash));
H->size=P;
H->cell=malloc(sizeof(struct node)*H->size);
while(P)
H->cell[--P].flag=-1;
return H;
}
int Hash(char *key,int P)//移位法散列映射,不考虑*key有几个字符
{
int h=0;
while(*key!='\0')
h=(h<<MAXB)+(*key++-'A');
return (h&MASK)%P;//最后用2^15-1的掩码,通过按位与将前面的清零
}
int Find(char *key,HashTable H)
{
int inc,count=0;
int next,pos;
next=pos=Hash(key,H->size);
while((H->cell[next].flag!=-1)&&strcmp(H->cell[next].data,key)!=0)
{
//若该位置已经被其他关键字占用,根据发生冲突的奇偶次数计算探测步长
if(++count%2)//奇数次冲突
inc=((count+1)*(count+1))>>2;
else//偶数次冲突
inc=-(count*count)>>2;
next=pos+inc;//平方探测
if(next<0)next=next+H->size;
else if(next>=H->size)
next=next-H->size;
}
return next;
}
void InsertAndOutput(char *key,HashTable H)
{
int pos=Find(key,H);
if(H->cell[pos].flag==-1)
{
H->cell[pos].flag=0;
strcpy(H->cell[pos].data,key);
}
printf("%d",pos);
}
main()
{
int N,P,i;
char key[MAXS+1];
HashTable H;
scanf("%d %d",&N,&P);
H=malloc(sizeof(struct hash));
H=Initial(P);
scanf("%s",key);
InsertAndOutput(key,H);
for(i=1;i<N;i++)
{
scanf("%s",key);
printf(" ");
InsertAndOutput(key,H);
}
printf("\n");
}
5-43 字符串关键字的散列映射
最新推荐文章于 2022-11-21 19:17:37 发布