#include <stdlib.h>
#include <string.h>
typedef struct _ {
struct _ * next;
char *key;
char *value;
} Node;
#define HASH_TABLE_SIZE 100
Node * initNode(char *key, char *value) {
if (key == NULL || value == NULL) {
Node *node = (Node *)malloc(sizeof(Node));
node->key = NULL;
node->value = NULL;
node->next = NULL;
return node;
} else {
Node *node = (Node *)malloc(sizeof(Node));
node->key = (char *)malloc(strlen(key) + 1);
strcpy(node->key, key);
node->value = (char *)malloc(strlen(value) + 1);
strcpy(node->value, value);
node->next = NULL;
return node;
}
}
int times33(char *key, int key_len) {
int hash = 5381;
for(int i = 0; i < key_len; i++) {
hash = ((hash << 5) + hash) + *key++;
}
return hash;
}
int initHashTable(Node **hashTable, int size) {
for(int i = 0; i < size; i++) {
*(hashTable + i) = initNode(NULL, NULL);
}
return 0;
}
int insertHashTable(Node **hashTable, int size, char *key, char *value) {
int hash_value = times33(key, strlen(key));
int arr_key = (size - 1) & hash_value;
Node *node = initNode(key, value);
node->next = *(hashTable + arr_key);
*(hashTable + arr_key) = node;
return 0;
}
char * searchValueByKey(Node **hashTable, int size, char *key) {
int hash_value = times33(key, strlen(key));
int arr_key = (size - 1) & hash_value;
Node *node = *(hashTable + arr_key);
while(node->key != NULL) {
if (strcmp(node->key, key) == 0) {
return node->value;
} else {
node = node->next;
}
}
return NULL;
}
int main(int argc, char** argv) {
Node *hashTable[HASH_TABLE_SIZE];
initHashTable(hashTable, HASH_TABLE_SIZE);
insertHashTable(hashTable, HASH_TABLE_SIZE, "name", "thomas");
insertHashTable(hashTable, HASH_TABLE_SIZE, "age", "19");
char *va = searchValueByKey(hashTable, HASH_TABLE_SIZE, "age");
printf("va = %sn", va);
return 0;
}
近期评论