#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<conio.h>
#define NAMESIZE 20//姓名長度
#define NULLKEY -32768//hash表空值
#define HASHSIZE 30//定義hash表長度
typedef struct student
{
char name[NAMESIZE];
int Snum;
int Tnum;
student *next=NULL;
}stu;
typedef struct
{
stu ** list;
int count;
}HashTable;
int InitHashtable(HashTable *hash)
{
hash->count=0;
hash->list=(stu **)malloc(HASHSIZE *sizeof(stu *));
if(!hash->list)
return -1;
for(int i=0;i<HASHSIZE;i++)
{
hash->list[i]=NULL;
}
return 1;
}
int hash(stu stu)
{
int hashseed=0;
for(int a=0;stu.name[a]!='\0';a++)
{
hashseed=hashseed*7+(int)stu.name[a];
}
int hashvalue=NULLKEY;
srand(hashseed);
hashvalue=rand()%HASHSIZE;
return hashvalue;
}
int intohashtable(HashTable *htable,student *stu)
{
int H1=hash(*stu);
if(htable->list[H1]!=NULL)//hash衝突
{
student *p;
p=(student *)malloc(sizeof(student));
p=stu;
p->next=htable->list[H1];
htable->list[H1]=p;
}
else
htable->list[H1]=stu;
htable->count++;
return 1;
}
int addstudent(HashTable *htable)
{
char name[NAMESIZE];
int snum,tnum;
stu *stu1;
stu1=(student *)malloc(sizeof(student));
printf("請輸入姓名:\t");fflush(stdin);
scanf("%s",name);
printf("請輸入學號:\t");
scanf("%d",&snum);
printf("請輸入電話號:\t");
scanf("%d",&tnum);
if(!name)
{
printf("addstudent__error");
return 0;
}
strcpy(stu1->name,name);
stu1->Snum=snum;
stu1->Tnum=tnum;
stu1->next=NULL;
if(intohashtable(htable,stu1))
return 1;
else
{
printf("into_error");
return 0;
}
}
int findhashtable(HashTable *htable)
{
printf("\t2-查詢\n");
char name[NAMESIZE];
printf("請輸入要查詢的姓名:");
scanf("%s",name);
stu stu0;
strcpy(stu0.name,name);
stu0.next=NULL;
stu0.Snum=0;
stu0.Tnum=0;
int hashkey;
hashkey=hash(stu0);
if(htable->list[hashkey]==NULL)
printf("查詢的值不存在\n");
if(htable->list[hashkey!=NULL])
{
stu *p;
p=htable->list[hashkey];
while(p)
{
if(name==p->name)
printf("你找的資訊為:\n姓名:%s\t學號:%d\t電話號碼%d\n",htable->list[hashkey]->name,htable->list[hashkey]->Snum,htable->list[hashkey]->Tnum);
if(p->next==NULL)
break;
p=p->next;
}
}
printf("你找的資訊為:\n姓名:%s\t學號:%d\t電話號碼%d\n",htable->list[hashkey]->name,htable->list[hashkey]->Snum,htable->list[hashkey]->Tnum);
getch();
}
int main()
{
HashTable *htable;
htable =(HashTable *)malloc(sizeof(HashTable));
InitHashtable(htable);
int T=1;
for(int a=1;T;a++)
{
system("cls");
printf("\t雜湊表設計實驗\n");
printf("1-新增\n2-查詢\n3-輸出hash表\n0-退出\n");
scanf("%d",&T);
if(T==1)
for(char c;1;1)
{
if(!addstudent(htable))
printf("addstudent返回error\n");
printf("是否繼續輸入如 y/n:\t");
fflush(stdin);
c=getchar();
if(c=='n'||c=='N')
break;
}
if(T==2)
findhashtable(htable);
if(T==3)
{
student *p;
printf("儲存的資料個數為%d個\n",htable->count);
for(int a=0;a<HASHSIZE;a++)
{
printf("%d\t",a);
p=htable->list[a];
int t=0;
while(p)
{
t=1;
printf("%s\t",p->name);
// if(p->next==NULL)
// break;
p=p->next;
}
if(t==0)
printf("0");
printf("\n");
}
getch();
}
}
}