c语言实现用链地址法处理哈希冲突的哈希查找
时间: 2024-03-25 21:37:43 浏览: 28
好的,下面是使用链地址法处理哈希冲突的哈希查找的C语言实现代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 20
typedef struct node {
int key;
char *value;
struct node *next;
} Node;
Node *hashTable[SIZE];
int hashFunction(int key) {
return key % SIZE;
}
void insert(int key, char *value) {
int index = hashFunction(key);
Node *newNode = (Node *) malloc(sizeof(Node));
newNode->key = key;
newNode->value = value;
newNode->next = NULL;
if (hashTable[index] == NULL) {
hashTable[index] = newNode;
} else {
Node *temp = hashTable[index];
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
char *search(int key) {
int index = hashFunction(key);
Node *temp = hashTable[index];
while (temp != NULL) {
if (temp->key == key) {
return temp->value;
}
temp = temp->next;
}
return NULL;
}
int main() {
insert(1, "apple");
insert(2, "banana");
insert(3, "cat");
insert(4, "dog");
printf("%s\n", search(2)); // banana
printf("%s\n", search(3)); // cat
printf("%s\n", search(5)); // NULL
return 0;
}
```
以上代码中,我们使用了一个大小为20的哈希表,并且实现了一个简单的哈希函数,即将键值对的键值取模。如果在插入时发现哈希表中对应位置为空,则直接插入该节点,否则在该位置的链表末尾插入新节点。在查找时,首先通过哈希函数计算出对应位置,然后遍历该位置的链表,寻找键值等于查找值的节点。如果找到了,则返回该节点的值,否则返回NULL。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)