您的位置:首页 > 其它

【算法】哈希表

2015-11-16 20:42 417 查看
本文介绍的是链式哈希表,如下图,展示一下结构:



代码是也是参考了一篇博客后更改的:

[code]
#define CALLENofHASHELEM  //计算表元素拉链长
#ifdef CALLENofHASHELEM
int Hashlenbuf[TABLELEN];
#endif

/*定义hash表和基本数据节点*/
typedef struct _NODE
{
    ElemType index;
    struct _NODE *next;
    void *data;
}NODE;

typedef struct _HASH_TABLE
{
    NODE *value[TABLELEN];
}HASH_TABLE;

typedef enum _status
{
    FALSE = 0,
    TRUE = 1
}STATUS;

/*创建hash表*/
HASH_TABLE *create_hash_table()
{
    HASH_TABLE *pHashTbl = (HASH_TABLE*)malloc(sizeof(HASH_TABLE));
    memset(pHashTbl, 0 ,sizeof(HASH_TABLE));
    return pHashTbl;
}

/*在hash表中查找数据*/
NODE* find_data_in_hash(HASH_TABLE *pHashTbl, ElemType index)
{
    NODE *pNode;
    if(NULL == pHashTbl)
        return NULL;

    if(NULL == (pNode = pHashTbl->value[index % TABLELEN]))
        return NULL;

    while(pNode)
    {   
//      printf("*"); //debug
        if(index == pNode->index)
            return pNode;
        pNode = pNode->next;
    }
    return NULL;
}

/*在hash表中插入数据*/
STATUS insert_data_into_hash(HASH_TABLE *pHashTbl, ElemType index, void *information)
{
    NODE *pNode;
    if(NULL == pHashTbl)
        return FALSE;

    if(NULL == pHashTbl->value[index % TABLELEN])
    {
        pNode = (NODE *)malloc(sizeof(NODE));
        memset(pNode, 0, sizeof(NODE));
        pNode->index = index;
        pNode->data = information;
        pHashTbl->value[index % TABLELEN] = pNode;
        return TRUE;
    }

    if(NULL != find_data_in_hash(pHashTbl, index))
        return FALSE;

    pNode = pHashTbl->value[index % TABLELEN];
    while(NULL != pNode->next)
        pNode = pNode->next;

    pNode->next = (NODE *)malloc(sizeof(NODE));
    memset(pNode->next, 0, sizeof(NODE));
    pNode->next->index = index;
    pNode->next->data = information;
//  pNode->next->next = NULL;
    return TRUE;

}

/*从hash中删除数据*/
STATUS delete_data_from_hash(HASH_TABLE *pHashTbl, ElemType index)
{
    NODE *pHead;
    NODE *pNode;
    if(NULL == pHashTbl || NULL == pHashTbl->value[index % TABLELEN])
        return FALSE;

    if(NULL == (pNode = find_data_in_hash(pHashTbl, index)))
        return FALSE;

    if(pNode == pHashTbl->value[index % TABLELEN])
    {
        pHashTbl->value[index % TABLELEN] = pNode->next;
        goto final;
    }

    pHead = pHashTbl->value[index % TABLELEN];
    while(pNode != pHead->next)
        pHead = pHead->next;
    pHead->next = pNode->next;

final:
    free(pNode);
    return TRUE;
}


配上实例工程代码(vs2010编译环境):点我获取或打开以下链接

http://download.csdn.net/detail/u012819339/9274341
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: