编辑代码

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

#define TABLE_SIZE 1000 // 设置一个足够大的表来避免冲突

typedef struct {
    char *voter_id;
} Vote;

Vote *hash_table[TABLE_SIZE];

// 简单的哈希函数
unsigned int hash(char *id) {
    unsigned long hash = 0;
    unsigned int c;

    while (c = (unsigned int)*id++) {
        hash = hash * 37 + c;
    }

    return hash % TABLE_SIZE;
}

// 插入投票者ID到散列表
int insert(char *voter_id) {
    unsigned int index = hash(voter_id);

    if (hash_table[index] != NULL) {
        return 0; // 已经投过票
    }

    hash_table[index] = malloc(sizeof(Vote));
    hash_table[index]->voter_id = strdup(voter_id); // 复制ID到哈希表中
    return 1; // 投票成功
}

// 测试函数
int main() {
    char *voters[] = {"Alice", "Bob", "Charlie", "David", NULL};
    char **current_voter = voters;

    while (*current_voter != NULL) {
        if (insert(*current_voter)) {
            printf("%s has voted successfully.\n", *current_voter);
        } else {
            printf("%s is trying to vote again!\n", *current_voter);
        }
        current_voter++;
    }

    // 投票结束后,清理散列表
    for (int i = 0; i < TABLE_SIZE; i++) {
        if (hash_table[i] != NULL) {
            free(hash_table[i]->voter_id);
            free(hash_table[i]);
        }
    }

    return 0;
}