已知哈希表装填因子小于1,哈希函数为关键字第一个字母在字母表中的序号,处理冲突的方法为线性探测开放地址法,编写一个按第一个字母的顺序输出哈希表中所有关键字的程序。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define m 29
#define MAXSIZE 20
#define SUCCESS 1
#define UNSUCCESS 0
#define DUPLICATE -1
typedef int Status;
typedef struct
{
char s[MAXSIZE];
}String;
typedef struct
{
String H[m];
int num;
}HashTable;
int Hash(String s);
void Collision(int *p,int c);
Status SearchHash(HashTable T,String k,int *p,int *c);
Status InsertHash(HashTable *T,String e);
void Output(HashTable T);
int main()
{
HashTable T;
int i;
for(i=0;i<m;i++)
T.H[i].s[0]='\0';
T.num=0;
String e;
printf("Input the keys to create the HashTable:");
scanf("%s",e.s);
i=Hash(e);
while(i>=0 && i<27)
{
InsertHash(&T,e);
printf("Input the keys to create the HashTable--0 to quit:");
scanf("%s",e.s);
i=Hash(e);
}
Output(T);
return 0;
}
int Hash(String s)
{
int t;
char c;
c=toupper(s.s[0]);
t=(int)(c-'A');
return t;
}
void Collision(int *p,int c)
{
*p=((*p)+1)%m;
}
Status SearchHash(HashTable T,String k,int *p,int *c)
{
*p=Hash(k);
while(*c<m && T.H[*p].s[0] && strcmp(T.H[*p].s,k.s))
Collision(p,++(*c));
if(!strcmp(T.H[*p].s,k.s))
return SUCCESS;
else
return UNSUCCESS;
}
Status InsertHash(HashTable *T,String e)
{
int p;
int c=0;
if(SearchHash(*T,e,&p,&c))
{
printf("There is already %s at H[%d]\n",e.s,p);
return DUPLICATE;
}
else if(c==m)
{
printf("The Table is full!\n");
return UNSUCCESS;
}
else
{
T->H[p]=e;
T->num++;
printf("Done!\n");
printf("There are %d numbers in the Table.\n",T->num);
return SUCCESS;
}
}
void Output(HashTable T)
{
int i;
for(i=0;i<26;i++)
{
String a;
int n=0;
a=T.H[i];
while(a.s[0])
{
int t;
t=Hash(a);
if(i==t)
printf("%s ",a.s);
a=T.H[(++n+i)%m];
}
}
}