哈希表总结-C语言版

目录

 

1、哈希表的原理

2、自己实现的hash表--C语言版

3、C语言开源项目uthash.h 中的hash接口 使用指南

3.1 uthash.h头文件说明

3.2 常见的uthash.h接口以及使用方法

4、实践应用

参考资料:

1、哈希表的原理

哈希表的关键思想是使用哈希函数将键映射到存储桶。更确切地说,

当我们插入一个新的键时,哈希函数将决定该键应该分配到哪个桶中,并将该键存储在相应的桶中;
当我们想要搜索一个键时,哈希表将使用相同的哈希函数来查找对应的桶,并只在特定的桶中进行搜索。

哈希表总结-C语言版_第1张图片

哈希表常用来搜索查找需要的元素, 哈希表的查找时间复杂度通常很低, 这里没有深入研究他的复杂度如何计算。

2、自己实现的hash表--C语言版

实现hash这种数据结构, 主要考虑两点:

(1)哈希函数:能够将集合中任意可能的元素映射到一个固定范围的整数值,并将该元素存储到整数值对应的地址上。
(2)冲突处理:由于不同元素可能映射到相同的整数值,因此需要在整数值出现「冲突」时,需要进行冲突处理。总的来说,有以下几种策略解决冲突:

本文使用链表的方式存储相同hash哈希值的元素, 因此代码中有链表的常见操作, 如链表创建、插入、删除、查找。

基于链表的操作, 完成了hash表的 创建、查找、插入、删除等操作。

代码如下:


typedef struct _ListNode_{
    int val;
    struct _ListNode_ *next;
} stListNode;

typedef struct {
    stListNode *data;
} MyHashSet;

/** Initialize your data structure here. */
//参考官方题解-- 用链表存储每一个key对应的不同的value,也就是解决冲突


/* 先完成链表的基本操作 */
// 在头结点之后插入一个新的节点
void ListPush(stListNode *head, int key)
{
    stListNode *tmp = (stListNode *)malloc(sizeof(stListNode));

    tmp->val = key;
    tmp->next = head->next;
    head->next = tmp;
}


void ListDelete(stListNode *head, int key)
{
    stListNode *it = head;
    stListNode *tmp = NULL;

    while(it->next)
    {
        if(key == it->next->val)
        {
            tmp = it->next;
            it->next = tmp->next;
            free(tmp);
            break;
        }  

        it = it->next; 
    }
}

//查找链表中是否存在key, 存在返回1, 不存在返回0
int ListContains(stListNode *head, int x)
{
    stListNode *it = head;

    //这里必须是it->next开头, 不然的话就会在头一次调用时判断失误, 具体原因不清楚???
    while(it->next)     
    {
        if(it->next->val == x)
        {
            return 1;
        }

        it = it->next;
    }

    return 0;
}

//删除链表的所有节点
void listFree(stListNode *head)
{
    while(head->next)
    {
        stListNode *tmp = head->next;
        head->next = tmp->next;
        free(tmp);
    }
}

const int base = 769;

int hash(int key) 
{
    return key % base;
}


//创建一个hash表, 里面可以存储base个key键值桶
MyHashSet* myHashSetCreate(void) 
{
    MyHashSet *rethash = (MyHashSet *)malloc(sizeof(MyHashSet));
    rethash->data = (stListNode *)malloc(sizeof(stListNode) * base);

    for(int i=0; idata[i].val = 0;
        rethash->data[i].next = NULL;
    }

    return rethash;  
}

//插入时先判断是否存在, 不存在时再插

你可能感兴趣的:(Leetcode刷题,哈希表)