C语言:hashTable

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

typedef int (*Func)(int, int);

//拉链法
//链表节点,数据域存字符串
typedef struct Node{
	Func func;
	struct Node *next;
}Node;

typedef struct
{
	char *funcName;
	Func func;
}funcTable;

int add(int a, int b)
{
	printf("add\n");
	return a+b;
}

int sub(int a, int b)
{
	printf("sub\n");
	return a-b;
}

//顺序表(表头,大小)
typedef struct HashTable{
	//链表首地址,是链表头结点的顺序表,由于头结点是Node *,顺序表示Node **
	Node **data;
	int size;
}HashTable;

//初始化链表,头插法,产生的新节点的next = 传入节点
Node *init_node(Func func, Node *head){
	Node *p = (Node *)malloc(sizeof(Node));
	p->func = func;
	p->next = head;
	return p;//虚拟头结点
}

HashTable *init_hashtable(int n){
	HashTable *h = (HashTable *)malloc(sizeof(HashTable));
	//h->size = n << 1;//若要使哈希表存储效率变高,存储空间扩大一倍??
	h->size = n;	
	h->data = (Node **)calloc(h->size, sizeof(Node *));
	return h;
}

void clear_node(Node *node){
	if (node == NULL) return;
	Node *p = node, *q;
	while(p){
		q = p->next;
		free(p);
		p = q;
	}
	free(q);//?
	return;
}

void clear_hashtable(HashTable *h){
	if (h == NULL) return;
	for (int i = 0; i < h->size; i++){
		clear_node(h->data[i]);
	}
	free(h->data);
	free(h);
	return;
}

int BKDRHash(char *str){
	int seed = 31, hash = 0;
	for (int i = 0; str[i]; i++) hash = hash * seed + str[i];
	//保证正数
	return hash & 0x7fffffff;
}

int insert(HashTable *h, char *str, Func func){
	int hash = BKDRHash(str);
	int ind = hash % h->size;
	printf("ind:%d\n", ind);
	h->data[ind] = init_node(func, h->data[ind]);
	return 1;
}

Func search(HashTable *h, char *str){
	int hash = BKDRHash(str);
	int ind = hash % h->size;
	Node *p = h->data[ind];
	//while (p && strcmp(str, p->str)) p = p->next;
	if (p != NULL)
	{
		return p->func;
	}	
	return NULL;
}

static funcTable gfuncTable[] = {
	{"func_add", add},
	{"test1", NULL},
	{"test2", NULL},
	{"test3", NULL},
	{"func_sub", sub},
	{"test4", NULL},
	{"test5", NULL},
	{"test6", NULL},
};
 
int main(){
	
	HashTable *h = init_hashtable(sizeof(gfuncTable)/sizeof(funcTable));
	for (int i = 0; i < sizeof(gfuncTable)/sizeof(funcTable); i++)
	{
		insert(h, gfuncTable[i].funcName, gfuncTable[i].func);
	}
	
	Func funcAdd = search(h, "func_add");
	printf("add:%d\n", funcAdd(1, 2));
	
	Func funcSub = search(h, "func_sub");
	printf("sub:%d\n", funcSub(7, 2));
	
	return 0;
}

参考链接:https://blog.csdn.net/one_chow_chow/article/details/109561575

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值