编辑代码

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

#define TABLE_SIZE 100

// 定义投票者结构体
typedef struct {
    char name[50];
    int voted;  // 记录是否已经投过票,0表示未投,1表示已投
} Voter;

// 定义哈希表节点
typedef struct {
    char* key;
    Voter* voter;
} Node;

// 定义哈希表
Node* hashTable[TABLE_SIZE];

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

// 哈希函数,将字符串映射为哈希表的索引
int hashFunction(char* key) {
    int hash = 0;
    while (*key) {
        hash += *key;
        ++key;
    }
    return hash % TABLE_SIZE;
}

// 在哈希表中查找投票者是否已经投过票
int searchVoter(char* name) {
    int index = hashFunction(name);

    // 查找散列表
    while (hashTable[index] != NULL) {
        if (strcmp(hashTable[index]->key, name) == 0) {
            // 找到了,表示已经投过票
            return 1;
        }

        // 散列冲突,采用线性探测法继续查找
        index = (index + 1) % TABLE_SIZE;
    }

    // 没找到,表示未投过票
    return 0;
}

// 在哈希表中插入投票者信息
void insertVoter(char* name) {
    int index = hashFunction(name);

    // 查找可用的位置
    while (hashTable[index] != NULL) {
        // 散列冲突,采用线性探测法继续查找
        index = (index + 1) % TABLE_SIZE;
    }

    // 创建新的节点并插入
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->key = strdup(name); // 使用strdup复制字符串,避免指针问题
    newNode->voter = (Voter*)malloc(sizeof(Voter));
    strcpy(newNode->voter->name, name);
    newNode->voter->voted = 1;

    hashTable[index] = newNode;
}

// 释放哈希表内存
void freeHashTable() {
    for (int i = 0; i < TABLE_SIZE; ++i) {
        if (hashTable[i] != NULL) {
            free(hashTable[i]->key);
            free(hashTable[i]->voter);
            free(hashTable[i]);
        }
    }
}

int main() {
    // 初始化哈希表
    initializeHashTable();

    // 模拟投票过程
    char names[][50] = {"Alice", "Bob", "Charlie", "Alice", "David", "Bob"};
    int numVoters = sizeof(names) / sizeof(names[0]);

    for (int i = 0; i < numVoters; ++i) {
        char* voterName = names[i];

        // 检查是否已经投过票
        if (searchVoter(voterName) == 0) {
            // 未投过票,进行投票并记录
            printf("%s投票成功!\n", voterName);
            insertVoter(voterName);
        } else {
            // 已经投过票,输出提示信息
            printf("%s已经投过票,不能重复投票。\n", voterName);
        }
    }

    // 释放哈希表内存
    freeHashTable();

    return 0;
}