这里的讲解实例用的是哈希表的链地址法
哈希表原作者博客:https://blog.csdn.net/weixin_40204595/article/details/81584679?utm_medium=distribute.pc_relevant.none-task-blog-utm_term-2&spm=1001.2101.3001.4242
哈希表的剩余代码可以去原作者博客参考,原作者讲的挺好,不过有一点小瑕疵,需要看下面的评论
头插法
int harsh_table_insert_node(const char * sKey, int nValue) {
HarshNode *pHarshNodeHead = NULL; //保存数组头节点地址
HarshNode *pNewNode = (HarshNode *) malloc(sizeof(HarshNode)); //为新节点分配空间
unsigned int pos = 0x0;
if (NULL == pNewNode) {
return -1; //-1的话分配出问题
}
memset(pNewNode, 0, sizeof(HarshNode)); //初始化新节点
pNewNode->sKey = (char *) malloc(strlen(sKey) + 1); //申请一块sKey大小的内存
if (NULL == pNewNode->sKey) {
return -1; //-1的话分配出问题
}
memset(pNewNode->sKey, 0, strlen(sKey) + 1);
strcpy(pNewNode->sKey, sKey); //将sKey的内容赋给 pNewNode -> sKey
pNewNode->nValue = nValue; //键值也复制过来
pNewNode->pNext = NULL;
if ((g_harsh_table_size >= HARSH_TABLE_MAX_SIZE) || (NULL == sKey))//分配地址
return -1;
pos = harsh_table_harsh_string(sKey) % HARSH_TABLE_MAX_SIZE; //用这种方法计算sKey在哈希数组中对应的位置
pHarshNodeHead = harshTable[pos]; //得到对应位置数组头节点
if (NULL == pHarshNodeHead) { //判断头节点是否为NULL
printf("harsh_table_insert_node:NULL == pHarshNodeHead\n");
harshTable[pos]= pNewNode; //如果为空,直接赋值
}
else { //如不为空
pNewNode ->pNext = harshTable[pos] ; //头插法,由于是新节点,也是头节点,所以pNext指向原来的头
harshTable[pos] = pNewNode; //最后一定要让数组中的这个位置指向这个头指针
}
g_harsh_table_size ++;
return 0;
}
尾插法稍微有一点复杂
int harsh_table_insert_node(const char * sKey, int nValue) {
HarshNode *pHarshNodeHead = NULL; //保存数组头节点地址
HarshNode *node = NULL; // 此指针用来保存数组最后一个不为空的节点地址
HarshNode *pNewNode = (HarshNode *) malloc(sizeof(HarshNode)); //为新节点分配空间
unsigned int pos = 0x0;
if (NULL == pNewNode) {
return -1;//-1的话分配出问题
}
memset(pNewNode, 0, sizeof(HarshNode));
pNewNode->sKey = (char *) malloc(strlen(sKey) + 1); //申请一块sKey大小的内存
if (NULL == pNewNode->sKey) {
return -1;
}
memset(pNewNode->sKey, 0, strlen(sKey) + 1);
strcpy(pNewNode->sKey, sKey); //将sKey的内容赋给 pNewNode -> sKey
pNewNode->nValue = nValue; //键值也复制过来
pNewNode->pNext = NULL;
if ((g_harsh_table_size >= HARSH_TABLE_MAX_SIZE) || (NULL == sKey))//分配地址
return -1;
pos = harsh_table_harsh_string(sKey) % HARSH_TABLE_MAX_SIZE; //用这种方法计算sKey在哈希数组中对应的位置
pHarshNodeHead = harshTable[pos];
if (NULL == pHarshNodeHead) { //判断头节点是否为NULL
printf("harsh_table_insert_node:NULL == pHarshNodeHead\n");
harshTable[pos]= pNewNode; //如果为空,直接赋值
}
else {
while (NULL != pHarshNodeHead) // 如果这个位置对应的不是这一串中最后一个节点的话,那就要向后移动了
{
if (strcmp(pHarshNodeHead->sKey, sKey) == 0) //如果这个键值对已经存在,只更新键值即可
{
pHarshNodeHead->nValue = nValue;
return 0;//如果已存在,更新完直接返回,不必再指向数据头节点
}
node = pHarshNodeHead; //保存这个不是NULL的节点地址,最后连接用
pHarshNodeHead = pHarshNodeHead->pNext; //向后移动,肯定会有NULL的时候
}
//这时,已经到了最后一个地址为NULL的节点
pHarshNodeHead = (HarshNode *) malloc(sizeof(HarshNode)); //分配空间
pHarshNodeHead = pNewNode; //赋值
node->pNext = pHarshNodeHead; //这一步很重要,将新节点与原链表连接
}
g_harsh_table_size ++;
return 0;
}