C语言算法与数据结构——hashmap(板子)

巧了我就是萌 提交于 2019-12-30 02:56:09
#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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!