编辑代码

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

#define HASH_SIZE 100

struct candidate {
    char name[20];
    int votes;
};

int hash_func(char *str, int size) {
    unsigned long hash = 5381;
    int c;
    while ((c = *str++) != '\0') {
        hash = ((hash << 5) + hash) + c;
    }
    return hash % size;
}

struct hash_table {
    struct candidate *data;
    int 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;
    memset(hash_tbl->data, 0, sizeof(struct candidate) * size);
    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++;
}

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() {
    int n;
    printf("请输入候选人数量:");
    scanf("%d", &n);

    struct hash_table *hash_tbl = create_hash_table(HASH_SIZE);
    for (int i = 0; i < n; i++) {
        char name[20];
        printf("请输入候选人姓名:");
        scanf("%s", name);
        insert_candidate(hash_tbl, name);
    }

    struct candidate *winner = find_winner(hash_tbl);
    printf("当选人姓名:%s,得票数:%d\n", winner->name, winner->votes);

    free(hash_tbl->data);
    free(hash_tbl);
    return 0;
}