编辑代码

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

#define MAX_CANDIDATES 100

typedef struct {
    char name[50];
    int votes;
} Candidate;

typedef struct {
    Candidate candidates[MAX_CANDIDATES];
    int count;
} HashTable;

// 哈希函数,用于计算字符串的哈希值
unsigned int hash(const char* str) {
    unsigned int hash = 5381;
    int c;

    while ((c = *str++)) {
        hash = ((hash << 5) + hash) + c; // 使用简单的哈希函数
    }

    return hash % MAX_CANDIDATES;
}

// 初始化散列表
void initialize_hash_table(HashTable* table) {
    table->count = 0;
    for (int i = 0; i < MAX_CANDIDATES; i++) {
        table->candidates[i].votes = 0;
        strcpy(table->candidates[i].name, ""); // 将候选人姓名置为空字符串
    }
}

// 添加投票
void add_vote(HashTable* table, const char* candidate_name) {
    unsigned int index = hash(candidate_name); // 计算候选人姓名的哈希值

    // 处理哈希冲突,使用线性探测法
    while (strcmp(table->candidates[index].name, "") != 0) {
        if (strcmp(table->candidates[index].name, candidate_name) == 0) {
            table->candidates[index].votes++; // 如果候选人已经存在,增加其得票数
            return;
        }

        index = (index + 1) % MAX_CANDIDATES; // 线性探测法,查找下一个位置
    }

    strcpy(table->candidates[index].name, candidate_name); // 将候选人姓名存储在找到的空位置
    table->candidates[index].votes++; // 增加候选人的得票数
    table->count++; // 增加计数器
}

// 打印投票结果
void print_results(const HashTable* table) {
    for (int i = 0; i < MAX_CANDIDATES; i++) {
        if (strcmp(table->candidates[i].name, "") != 0) {
            printf("%s获得 %d 票\n", table->candidates[i].name, table->candidates[i].votes);
        }
    }
}

int main() {
    HashTable vote_table;
    initialize_hash_table(&vote_table); // 初始化散列表

    // 添加投票
    add_vote(&vote_table, "许许");
    add_vote(&vote_table, "许许");
    add_vote(&vote_table, "希希");
    add_vote(&vote_table, "许许");
    add_vote(&vote_table, "嘻嘻");
    add_vote(&vote_table, "嘻嘻");
   

    // 打印结果
    print_results(&vote_table);

    return 0;
}