使用Hash表实现英文单词表并实现单词查询操作:

1个回答

  • #include

    #include

    #include

    #define N 100//散列表长度

    struct Node

    {

    char* key; char* val;

    Node* next;

    }*heads[N];//散列表,用链处理冲突

    int hash(char* key)//散列函数

    {

    unsigned long h=0;

    while(*key)

    {

    h=(h24;

    h&=~g;

    }

    return h&N;

    }

    Node* find(char* key)//查找

    {

    Node* cur=heads[hash(key)];

    while(cur)

    {

    if(!strcmp(cur->key,key))

    return cur;

    cur=cur->next;

    }

    return NULL;

    }

    void insert(char* key,char* val)//插入

    {

    int i=hash(key);

    Node* head=heads[i];

    if(find(key)==NULL)

    {

    Node* tmp=(Node*)malloc(sizeof(Node));

    tmp->key=(char*)malloc(strlen(key)+1);

    tmp->val=(char*)malloc(strlen(val)+1);

    strcpy(tmp->key,key);

    strcpy(tmp->val,val);

    tmp->next=head;

    heads[i]=tmp;

    }

    }

    main()

    {

    char tmp[100],*key,*val;

    Node* cur;

    FILE *fp=fopen("abc.txt","r");

    if(fp==NULL)

    {

    printf("打开文件有问题n");

    exit(1);

    }

    while(fgets(tmp,100,fp)!=NULL)

    {

    if(tmp[strlen(tmp)-1]=='n')

    tmp[strlen(tmp)-1]=' ';

    key=strtok(tmp,"t");

    val=strtok(NULL,"t");

    insert(key,val);

    }

    printf("输入你要查找的单词:n");

    while(gets(tmp))

    {

    cur=find(tmp);

    if(cur==NULL)

    printf("没找到n");

    else

    printf("%sn",cur->val);

    }

    }