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

本文介绍了一种使用链地址法实现哈希表的方法,包括哈希表的创建、插入、查找等核心操作。通过具体代码展示了如何利用C语言进行数据结构的设计与实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值