#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;
}
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;
}
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() {
struct hash_table *hash_tbl = create_hash_table(HASH_SIZE);
char name[20];
int n = 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;
}