c语言实现通用数据结构(四):通用集合(HashSet)

本文介绍了如何在C语言中基于通用链表实现一个通用集合(HashSet),重点在于HashSet的存储特性以及如何为不同数据类型自定义HashCode函数和equal函数。内容包括链表实现、HashCode函数和equal函数的示例。
摘要由CSDN通过智能技术生成

这是在通用链表的基础上实现的集合,关于链表的实现参见:http://blog.csdn.net/swwlqw/article/details/22498833

注意集合中只存储了指针,没有储存实际的数据。

对于新的数据类型来说,需要自定义HashCode函数和equal函数。

下面还给出了几个常见的hashCode函数和equal函数。


(1)HashCode函数

头文件

/*************************
*** File myHashCode.h
**************************/
#ifndef MYHASHCODE_H_INCLUDED
#define MYHASHCODE_H_INCLUDED

#include <string.h>

#define HASHCODE_MULT 31

//默认的hashCode
int myHashCodeDefault(void * a);

//int类型hashCode
int myHashCodeInt(void * a);

//char类型的hashCode
int myHashCodeChar(void * a);

//string类型的hashCode
int myHashCodeString(void * a);

#endif // MYHASHCODE_H_INCLUDED


源文件

/*************************
*** File myHashCode.c
**************************/
#include "myHashCode.h"

//默认的hashCode
int myHashCodeDefault(void * a)
{
    return (int) a;
}

//int类型hashCode
int myHashCodeInt(void * a)
{
    int * aa = (int *) a;
    return *aa;
}

//char类型的hashCode
int myHashCodeChar(void * a)
{
    char *aa = (char *) a;
    return *aa;
}

//string类型的hashCode
int myHashCodeString(void * a)
{
    int re = 0;
    char *aa = (char *) a;
    while (*aa)
    {
        re += HASHCODE_MULT * *aa;
        aa++;
    }
    return re;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值