#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node* Link;
struct Node {
char data[15];
Link next;
int count;
};
typedef struct Table* hashtable;
struct Table {
int size;
//链地址法
Link heads;
};
hashtable creat(int s)
{
hashtable h = (hashtable)malloc((sizeof(struct Table)));
h->size = s;
h->heads = (Link)malloc(h->size * sizeof(struct Node));
int i;
//初始化表头结点
for(i = 0; i < s; i++) {
h->heads[i].data[0] = '\0';
h->heads[i].next = NULL;
h->heads[i].count = 0;
}
return h;
}
int hash(char *key, int s)
{
int h = 0;
while(*key != '\0')
h = ( h<<5 ) + *key++;
return h % s;
}
Link find(hashtable h, char *key)
{
Link p;
int pos;
pos = hash(key + 6, h->size);
p = h->heads[pos].next;
while(p && strcmp(p->data, key)) {
p = p->next;
}
return p;
}
void insert(hashtable h, char *key)
{
Link p, t;
int pos;
p = find(h, key);
if(p) {
p->count++;
} else {
t = (Link)malloc(sizeof(struct Node));
strcpy(t->data, key);
t->count = 1;
pos = hash(key+6, h->size);
t->next = h->heads[pos].next;
h->heads[pos].next = t;
}
}
void ans(hashtable h)
{
int i, cnt = 0;
int maxcnt = 0;
char minphone[15];
Link p;
for(i = 0; i < h->size; i++) {
p = h->heads[i].next;
while(p) {
if(p->count > maxcnt) {
maxcnt = p->count;
strcpy(minphone, p->data);
cnt = 0;
} else if(p->count == maxcnt) {
cnt++;
if(strcmp(minphone, p->data) > 0) strcpy(minphone, p->data);
}
p = p->next;
}
}
printf("%s %d", minphone, maxcnt);
if (cnt > 1) printf("%d", cnt);
}
int main()
{
int n;
char c1[15], c2[15];
scanf("%d", &n);
hashtable h = creat(n * 2);
int i;
for(i = 0; i < n; i++) {
scanf("%s %s",c1,c2);
insert(h, c1);
insert(h, c2);
}
ans(h);
return 0;
}
来源:CSDN
作者:面向案例编程
链接:https://blog.csdn.net/qq_42570673/article/details/103751569