c语言如何map

c语言如何map

#include

#include

#include

#define TABLE_SIZE 100

typedef struct Entry {

char *key;

char *value;

struct Entry *next;

} Entry;

typedef struct {

Entry *entries[TABLE_SIZE];

} HashTable;

unsigned int hash(const char *key) {

unsigned long int value = 0;

unsigned int i = 0;

unsigned int key_len = strlen(key);

for (; i < key_len; ++i) {

value = value * 37 + key[i];

}

value = value % TABLE_SIZE;

return value;

}

HashTable *create_table() {

HashTable *table = malloc(sizeof(HashTable));

for (int i = 0; i < TABLE_SIZE; i++) {

table->entries[i] = NULL;

}

return table;

}

void set(HashTable *table, const char *key, const char *value) {

unsigned int slot = hash(key);

Entry *entry = table->entries[slot];

if (entry == NULL) {

entry = malloc(sizeof(Entry));

entry->key = strdup(key);

entry->value = strdup(value);

entry->next = NULL;

table->entries[slot] = entry;

} else {

Entry *prev;

while (entry != NULL) {

if (strcmp(entry->key, key) == 0) {

free(entry->value);

entry->value = strdup(value);

return;

}

prev = entry;

entry = entry->next;

}

entry = malloc(sizeof(Entry));

entry->key = strdup(key);

entry->value = strdup(value);

entry->next = NULL;

prev->next = entry;

}

}

char *get(HashTable *table, const char *key) {

unsigned int slot = hash(key);

Entry *entry = table->entries[slot];

if (entry == NULL) {

return NULL;

}

while (entry != NULL) {

if (strcmp(entry->key, key) == 0) {

return entry->value;

}

entry = entry->next;

}

return NULL;

}

int main() {

HashTable *table = create_table();

set(table, "name", "Alice");

set(table, "age", "25");

printf("name: %sn", get(table, "name"));

printf("age: %sn", get(table, "age"));

return 0;

}

相关推荐

海信E71M,性能优越,物超所值(揭秘海信E71M的卓越性能与出色品质)
按的意思
365bet娱乐场官网备用

按的意思

📅 11-28 👁️ 5090
为什么大家都用iPhone? 热卖原因出自10大关键买iPhone的理由