5-14 电话聊天狂人

这里写图片描述

#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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值