#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#define MAXS 11
#define MAXD 5
typedef struct hashentry *List;
struct hashentry{
char phone[MAXS+1];
int count;
List next;
};
struct hash{
int size;
List thelist;//指向结构体List的指针数组
};
typedef struct hash *HashTable;
int nextprime(int N)
{
int i;
if(!(N%2))N++;
for(;;N=N+2)
{
for(i=(int)sqrt(N);i>2;i--)
if(!(N%i))break;
if(i==2)break;
}
return N;
}
HashTable create(int N)
{
HashTable T;
int i;
T=malloc(sizeof(struct hash));
T->size=nextprime(N);
T->thelist=malloc(sizeof(struct hashentry)*T->size);
for(i=0;i<T->size;i++)
{
T->thelist[i].phone[0]='\0';
T->thelist[i].count=0;
T->thelist[i].next=NULL;
}
return T;
}
int Hash(int key,int p)
{
return key%p;//除留余数法
}
void Insert(char *key,HashTable H)
{
List L,position,newposition;
L=&(H->thelist[Hash(atoi(key+6),H->size)]);//先找到散列映射后的位置
position=L->next; //在相应的链表中查找
while(position&&strcmp(position->phone,key))
position=position->next;
if(position)
position->count++;
else
{
newposition=malloc(sizeof(struct hash));
strcpy(newposition->phone,key);
newposition->count=1;
newposition->next=L->next;
L->next=newposition;
}
}
void output(HashTable H)
{
int max=0,num=0,i;//max最大通话次数,num狂人数
List L;
char s[MAXS+1];
s[0]='\0';
for(i=0;i<H->size;i++)
{
L=H->thelist[i].next;
while(L)
{
if(L->count>max)
{
max=L->count;
strcpy(s,L->phone);
num=1;
}
else if(L->count==max)
{
num++;
if(strcmp(s,L->phone)>0)
strcpy(s,L->phone);
}
L=L->next;
}
}
printf("%s %d",s,max);
if(num>1)
printf(" %d",num);
}
void freehash(HashTable H)
{
List L,tmp;
int i;
for(i=0;i<H->size;i++)
{
L=H->thelist[i].next;
while(L)
{
tmp=L->next;
free(L);
L=tmp;
}
}
free(H->thelist);
free(H);
}
main()
{
int N,i;
char a[MAXS+1];
HashTable H;
scanf("%d",&N);
H=create(N);
for(i=0;i<N;i++)
{
scanf("%s",a);
Insert(a,H);
scanf("%s",a);
Insert(a,H);
}
output(H);
freehash(H);
}
5-14 电话聊天狂人
最新推荐文章于 2021-02-23 20:47:15 发布