字符串哈希之散列表处理冲突 poj1880

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define M 100001
#define N 100

struct node       //链表数组
{
    int id;
    struct node *next;
}*d[M];  

char a[M][N],b[M][N]; 
char s[N],str[N];

unsigned int ELFHash(char *str)
{
    unsigned int hash=0;
    unsigned int x=0;
    while(*str)
    {
        hash=(hash<<4)+(*str++);
        if((x=hash&0xF0000000L)!=0)
        {
            hash^=(x>>24);
            hash&=~x;
        }
    }
    return hash%M;
}
int main()
{
    int i=0;
    struct node *p;
    while(scanf("%s",str),strcmp("@END@",str)) 
    {
        int len=strlen(str);
        str[len-1]='';
        strcpy(a[i],str+1); //前一个字符串处理
        gets(str);          //后一个字符串处理
        strcpy(b[i],str+1);
        
        int hash=ELFHash(b[i]);  //后一个字符串的映射
        p=(struct node *)malloc(sizeof(struct node));//创建动态链表p
        p->id=i;          //给值
        p->next=d[hash];  //给链表数组的第hash个链表给首地址
        d[hash]=p;        //将链表p的首地址付给链表数组的第hash个链表
        
        hash=ELFHash(a[i]);    //前一个字符串的映射,两个字符串的i值相同
        p=(struct node *)malloc(sizeof(struct node));
        p->id=i;
        p->next=d[hash];
        d[hash]=p;
        i++;
    }
    int n;
    scanf("%d",&n);
    getchar();
    while(n--)
    {
        gets(str);
        if(str[0]=='[')
        {
            int len=strlen(str);
            str[len-1]='';
            strcpy(s,str+1);
        }
        else
            strcpy(s,str);
        int hash=ELFHash(s);
        p=d[hash];
        int flag1=1,flag2=1;
        while(p)
        {
            if(strcmp(b[p->id],s)==0)
            {
                flag1=0;
                break;
            }
            if(strcmp(a[p->id],s)==0)
            {
                flag2=0;
                break;
            }
            p=p->next;
        }
        if(p)
        {
            if(flag1==0)
                printf("%s
",a[p->id]);
            else
                printf("%s
",b[p->id]);
        }
        else
            printf("what?
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/calmwithdream/p/5351906.html