#include<stdio.h> #include<stdlib.h> #include<string.h> #define N 30 typedef char elemtype[19]; typedef struct node { elemtype name; int num; }tablenode;/*定义结点类型*/ tablenode *L; void create_hash()/*伪随机法构造哈希表*/ { int i,sum; char string[19]; L=(tablenode *)malloc(N*sizeof(tablenode)); if(!L) { printf("\noverflow!"); exit(0); } for(i=0;i<N;i++) { L[i].name[0] ='\0'; L[i].num=i; } for(i=0;i<N;i++) { printf("\nplease input the name of the %dth student:",i+1); gets(string); sum=jisuan(string); if(insert_hash(sum,string)) printf("\ninsert node succeed!"); } } int suiji()/*产生随机数*/ { int di; randomize(); di=random(2*N); di=(N-di-1)%N; return di; } int insert_hash(int result,char *q)/*向哈希表中插入结点*/ { int num,flag=0; num=result%N; if(L[num].name[0]=='') { strcpy(L[num].name,q); flag=1; return flag; } else { result=result+suiji(); insert_hash(result,q); } } int hash_search(int x,char *s) { int i; i=x%N; if(strcmp(L[i].name,s)==0) { printf("\n find it at the %dth location!",i+1); return 1; } else { x=x+suiji(); hash_search(x,s); return 0; } } int jisuan(char *p)/*计算字符串的值*/ { int sum=0,di; for(;*p!='\0';p++) sum+=*p; return sum; } void search(void)/*伪随机法哈希表的查找*/ { elemtype new; int sum; printf("\nplease input the name of the student search:"); scanf("%s",new); sum=jisuan(new); if(!hash_search(sum,new)) { printf("\nnot exit the student!!!!"); getch(); return; } } main() { clrscr(); create_hash(); search(); }

评论