#include <stdio.h>
#include <stdlib.h>
#include "hashTable.h"
//散列函数--除法散列法
unsigned hash(char *key)
{
unsigned hashVal;
char *tmp = key;
for (hashVal = 0; *key != '\0'; key++)
{
hashVal = *key + 31 * hashVal;
}
hashVal = 2;
return hashVal;
}
//查询key
Nodelist *search(char *key)
{
Nodelist *np;
for (np = hashTable[hash(key)]; np != NULL; np = np->next)
{
if(strcmp(key, np->key) == 0)
return np;
}
return NULL;
}
//插入到哈希表
Nodelist *put(char *key, char *value)
{
Nodelist *np;
unsigned hashVal;
if((np = search(key)) == NULL)
{
np = (Nodelist *) malloc(sizeof(Nodelist));
if(np == NULL || (np->key = (char *)key) == NULL)
return NULL;
np->next = NULL;
hashVal = hash(key);
//如果不同key散列到同一个值,则用链表存起来
if(hashTable[hashVal] == NULL) {
hashTable[hashVal] = np;
}else {
Nodelist *npTmp = hashTable[hashVal], *preNp;
while(npTmp != NULL)
{
preNp = npTmp;
npTmp = npTmp->next;
}
preNp->next = np;
}
} else{
free((void*)np->value);
}
if ((np->value = (char *)value) == NULL)
return NULL;
return np;
}
//根据key获取值
void get(char *key)
{
Nodelist *np;
unsigned hashVal = hash(key);
np = (Nodelist *)hashTable[hashVal];
while(np != NULL)
{
if(strcmp(key, np->key) == 0) {
printf("key:%s value:%s\n", key, np->value);
break;
} else {
np = np->next;
}
}
if(np == NULL) printf("the key ");
}
哈希表-使用C语言实现哈希表数据结构-HashTable.zip
172 浏览量
2024-03-04
08:45:59
上传
评论
收藏 2KB ZIP 举报
极智视界
- 粉丝: 2w+
- 资源: 1330
最新资源
- 二叉树7-1-1.cpp
- android 9.0 原生模拟器 签名文件
- 技术面试最后反问面试官的话 校招面试非技术问题有哪些 非技术问题如何回答.png
- NB-IOT-BC26全网通模块Altium+ CADENCE +PADS三种格式(原理图SCH+PCB封装库)文件.zip
- 基于微信小程序开发的校园失物招领系统源码毕业设计(优质项目源码).zip
- 词向量是一种将自然语言中的单词转换为数值向量的技术,它能够捕捉词义和上下文信息
- nmap与masscan的简单使用
- MyBatis动态SQL.pdf
- 基于stm32单片机protues仿真的温湿度控制系统设计(仿真图、源代码)
- 词向量:自然语言处理的基石
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈