编辑代码

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define HASH_SIZE 100  //散列表大小

//定义候选人结构体
struct candidate {
    char name[20];  //候选人姓名
    int votes;      //候选人得票数
};

//定义散列表结构体
struct hash_table {
    struct candidate *data;  //结构体指针,指向候选人结构体
    int size;                //散列表大小
};

//哈希函数,将字符串转换为散列值
int hash_func(char *str, int size) {
    unsigned long hash = 5381;  //初始值,经验值
    int c;
    while ((c = *str++) != '\0') {
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
    }
    return hash % size;  //取模运算得到散列表下标
}

//创建散列表
struct hash_table* create_hash_table(int size) {
    struct hash_table *hash_tbl = (struct hash_table*)malloc(sizeof(struct hash_table));
    hash_tbl->data = (struct candidate*)malloc(sizeof(struct candidate) * size);
    hash_tbl->size = size;
    for (int i = 0; i < size; i++) {
        hash_tbl->data[i].name[0] = '\0';  //初始化候选人姓名为空串
        hash_tbl->data[i].votes = 0;       //初始化候选人得票数为0
    }
    return hash_tbl;
}

//插入候选人到散列表中
void insert_candidate(struct hash_table *hash_tbl, char *name) {
    int index = hash_func(name, hash_tbl->size);  //计算散列表下标
    while (hash_tbl->data[index].votes != 0 && strcmp(hash_tbl->data[index].name, name) != 0) {
        index = (index + 1) % hash_tbl->size;     //如果发生哈希冲突,则线性探测找到下一个空槽位
    }
    strcpy(hash_tbl->data[index].name, name);     //将候选人姓名存储到散列表中
    hash_tbl->data[index].votes++;                //将候选人得票数加1
}

//查找得票最高的候选人
struct candidate* find_winner(struct hash_table *hash_tbl) {
    struct candidate *winner = &hash_tbl->data[0];
    for (int i = 1; i < hash_tbl->size; i++) {
        if (hash_tbl->data[i].votes > winner->votes) {
            winner = &hash_tbl->data[i];  //更新得票最高的候选人
        }
    }
    return winner;
}

int main() {
    struct hash_table *hash_tbl = create_hash_table(HASH_SIZE);
    char name[20];
    int n = 5;  // 候选人数量为5
    char candidates[5][20] = {"张三", "李四", "王五", "赵六", "钱七"};
    for (int i = 0; i < n; i++) {
        insert_candidate(hash_tbl, candidates[i]);  // 将候选人添加到散列表中
    }
    struct candidate *winner = find_winner(hash_tbl);  // 查找得票最高的候选人
    printf("当选人姓名:%s,得票数:%d\n", winner->name, winner->votes);
    free(hash_tbl->data);   // 释放内存
    free(hash_tbl);
    return 0;
}