當前位置:編程學習大全網 - 編程軟體 - 使用Hash表實現英文單詞表並實現單詞查詢操作

使用Hash表實現英文單詞表並實現單詞查詢操作

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#define N 100//散列表長度

struct Node

{

char* key; char* val;

Node* next;

}*heads[N];//散列表,用鏈處理沖突

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

{

unsigned long h=0;

while(*key)

{

h=(h<<4)+*key++;

unsigned long g=h & 0xF0000000L;

if(g)

h^=g>>24;

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]='\0';

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("%s\n",cur->val);

}

}

  • 上一篇:C++中函數模板和模板函數的區別
  • 下一篇:惠州體育館在哪兒
  • copyright 2024編程學習大全網