5-43 字符串关键字的散列映射

这里写图片描述

#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");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值