用c写出散列查找的代码实现
时间: 2024-02-05 10:13:11 浏览: 32
下面是一个简单的散列查找的代码实现,使用的是开放地址法:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HASH_TABLE_SIZE 100
typedef struct {
char key[20];
int value;
} HashNode;
int hash(char *key) {
int sum = 0;
for (int i = 0; i < strlen(key); i++) {
sum += key[i];
}
return sum % HASH_TABLE_SIZE;
}
void insert(HashNode *hashTable, char *key, int value) {
int index = hash(key);
while (hashTable[index].value != -1) {
index++;
if (index == HASH_TABLE_SIZE) {
index = 0;
}
}
strcpy(hashTable[index].key, key);
hashTable[index].value = value;
}
int search(HashNode *hashTable, char *key) {
int index = hash(key);
while (hashTable[index].value != -1) {
if (strcmp(hashTable[index].key, key) == 0) {
return hashTable[index].value;
}
index++;
if (index == HASH_TABLE_SIZE) {
index = 0;
}
}
return -1;
}
int main() {
HashNode hashTable[HASH_TABLE_SIZE];
for (int i = 0; i < HASH_TABLE_SIZE; i++) {
hashTable[i].value = -1;
}
insert(hashTable, "apple", 1);
insert(hashTable, "banana", 2);
insert(hashTable, "orange", 3);
insert(hashTable, "watermelon", 4);
printf("The value of banana is %d.\n", search(hashTable, "banana"));
printf("The value of watermelon is %d.\n", search(hashTable, "watermelon"));
printf("The value of grape is %d.\n", search(hashTable, "grape"));
return 0;
}
```
在这个代码中,我们定义了一个 `HashNode` 结构体表示散列表中的一个元素。`hash` 函数将字符串键映射到散列表中的索引,使用的是字符串中字符 ASCII 码的加和再取余数的方法。`insert` 函数将键值对插入散列表,如果当前索引已经有元素了,则采用线性探测的方法寻找下一个空闲的位置。`search` 函数在散列表中查找指定的键,如果找到了则返回对应的值,否则返回 `-1`。在 `main` 函数中,我们初始化散列表并在其中插入一些数据,然后测试查找功能。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)