Hashtable - C语言实现

本文介绍了使用C语言实现Hashtable的程序要点,包括内存管理原则、哈希索引的计算方法、不允许添加相同键值对以及允许键相同但值不同的处理方式,具体实现通过单向链表存储于哈希表节点中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

程序要点:

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);
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值