编辑代码

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

#define TABLE_SIZE 100

// 定义投票者结构
typedef struct Node {
    char name[50];
    struct Node *next;
} Node;

// 定义散列表
Node *hashTable[TABLE_SIZE];

// 散列函数,这里简单地将字符串转换成一个整数作为索引
unsigned int hash(char *str) {
    unsigned int hash = 0;
    while (*str) {
        hash = (hash << 5) + *str++;
    }
    return hash % TABLE_SIZE;
}

// 初始化散列表
void initializeHashTable() {
    for (int i = 0; i < TABLE_SIZE; i++) {
        hashTable[i] = NULL;
    }
}

// 检查是否已经投过票
int hasVoted(char *name) {
    unsigned int index = hash(name);
    Node *current = hashTable[index];

    while (current != NULL) {
        if (strcmp(current->name, name) == 0) {
            return 1; // 已经投过票
        }
        current = current->next;
    }
    return 0; // 没有投过票
}

// 投票
void vote(char *name) {
    if (hasVoted(name)) {
        printf("%s 已经投过票了!\n", name);
    } else {
        unsigned int index = hash(name);
        Node *newNode = (Node *)malloc(sizeof(Node));
        if (newNode == NULL) {
            printf("内存分配失败\n");
            return;
        }
        strcpy(newNode->name, name);
        newNode->next = hashTable[index];
        hashTable[index] = newNode;
        printf("%s 成功投票!\n", name);
    }
}

int main() {
    initializeHashTable();

    vote("Alice"); // Alice 投票
    vote("Bob");   // Bob 投票
    vote("Alice"); // Alice 尝试再次投票

    return 0;
}