| 发表于:2007-07-30 15:41:1336楼 得分:0 |
随手写的, 运行了一下,还有很多错误.赫赫 #include "stdio.h " #define table_capacity 10000 typedef struct infors { int no; //id char name[10]; //姓名不应大于10个字符 struct infors *next; }infors, * pinfors; pinfors hashtable[table_capacity]={null}; int hashvalue(int id)//产生哈西值 { return id%10000; } void hash_set(int ikey,pinfors p) //设置哈西表 { int key; key=hashvalue(ikey); if(hashtable[key]==null) { hashtable[key]=p; } else //如果第一次的哈西值相同(冲突),那么将后来的链入链表的最后面 { pinfors cur; while((cur=hashtable[key]-> next)==null); cur-> next=p; } } int init_infors(int id,char * ps) { if(ps==null) return -1; pinfors p=(pinfors)malloc(sizeof(infors)); if(p!=null) { p-> no=id; strcpy(p-> name,ps); p-> next=null; hash_set(id,p); } return id; } void init() { for(int i=0;i <100000;i++) { char * pname=gets((char *)stdin); int rs=init_infors(i,pname); if(rs==-1) { printf( "第 %d 个数据初始化失败\n ",i); return; } } } //测试函数 int get_unit_no( void * info ) { pinfors p=(pinfors)info; return p-> no; //这里要保正 info指向的是真正的infors的数据结构,否则返回有可能出错,有可能是垃圾 } void * get_unit_info(int unit_no) { int index=hashvalue(unit_no); if(hashtable[index]-> no==unit_no) { return (void *)hashtable[index]; } else { pinfors cp=hashtable[index]; for(;cp-> next!=null;cp=cp-> next) { if(cp-> no==unit_no) return (void *)cp; } } } int main(int argc, _tchar* argv[]) { init(); return 0; } | | |
|