程序要点:
1. 原则上,谁malloc谁负责free;
2. hash_index的计算:使用key字符串每个字符之和% max_node_index;
3. 不允许添加相同的struct node *n,即对应的key=value已经在table中存在则添加失败;
4. 允许相同的key,但不同的value.以单向链表的形式存放于table->nodes[hash_index]中。
HashTable.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define RET_TRUE 0
#define RET_FALSE -1
struct node {
char *key;
char *value;
struct node *next;
};
struct hash_table {
struct node **nodes;
int max_node_index;
int (*hash)(struct hash_table *table, char *key);
int (*search)(struct hash_table *table, struct node *node);
int (*insert)(struct hash_table *table, struct node *node);
int (*delete)(struct hash_table *table, struct node *node);
};
static void free_node(struct node **n);
static struct node * create_node(char *key, char *value);
static int compare_node(struct node *dst, struct node *src);
static int malloc_and_copy_string(char **dst, char *src);
static int malloc_and_copy_node(struct node *dst, struct node *src);
static int hash(struct hash_table *table, char *key);
static int search(struct hash_table *table, struct node *node);
static int insert(struct hash_table *table, struct node *node);
static int delete(struct hash_table *table, struct node *node);
static int init_hashtable(struct hash_table *table, int size);
/*
* Compute the sum of each char value in key.
* hash_index = sum % hash_table.max_node_index
*/
static int hash(struct hash_table *table, char *key)
{
int len, hash_index, char_sum = 0;
char c;
if(NULL == table || table->max_node_index <= 0 || NULL == key)
return RET_FALSE;
//printf("hash for [%s] ", key);