编辑代码

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

#define TABLE_SIZE 1000

typedef struct Node {
    char *key;
    struct Node *next;
} Node;

typedef struct HashTable {
    Node *table[TABLE_SIZE];
} HashTable;

unsigned int hash_function(const char *key) {
    unsigned int hash = 0;
    for (int i = 0; key[i] != '\0'; i++) {
        hash = 31 * hash + key[i];
    }
    return hash % TABLE_SIZE;
}

Node *create_node(const char *key) {
    Node *new_node = (Node *)malloc(sizeof(Node));
    if (new_node != NULL) {
        new_node->key = strdup(key);
        new_node->next = NULL;
    }
    return new_node;
}

void insert(HashTable *ht, const char *key) {
    unsigned int index = hash_function(key);
    Node *new_node = create_node(key);
    if (new_node == NULL) {
        fprintf(stderr, "Memory allocation failed");
        return;
    }
    new_node->next = ht->table[index];
    ht->table[index] = new_node;
}

int search(HashTable *ht, const char *key) {
    unsigned int index = hash_function(key);
    Node *current = ht->table[index];
    while (current != NULL) {
        if (strcmp(current->key, key) == 0) {
            return 1;  // 找到相同的投票者
        }
        current = current->next;
    }
    return 0;  // 没有找到相同的投票者
}

int main() {
    HashTable ht;
    for (int i = 0; i < TABLE_SIZE; i++) {
        ht.table[i] = NULL;
    }

    insert(&ht, "voter 1");
    insert(&ht, "voter 2");
    insert(&ht, "voter 3");

    if (search(&ht, "voter 1")) {
        printf("voter 1 has already voted\n");
    } else {
        printf("voter 1 has not voted yet\n");
    } 
   if (search(&ht, "voter 2")) {
        printf("voter 2 has already voted\n");
    } else {
        printf("voter 2 has not voted yet\n");
    } 
    if (search(&ht, "voter 4")) {
        printf("voter 4 has already voted\n");
    } else {
        printf("voter 4 has not voted yet\n");
    }

    return 0;
}