用C语言实现Hash查找
时间: 2023-07-18 13:14:45 浏览: 62
好的,以下是用C语言实现Hash查找的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
struct Node {
int key;
int value;
struct Node* next;
};
struct HashTable {
struct Node* data[SIZE];
};
int hash_func(int key) {
return key % SIZE;
}
void insert(struct HashTable* ht, int key, int value) {
int index = hash_func(key);
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->key = key;
node->value = value;
node->next = NULL;
if (ht->data[index] == NULL) {
ht->data[index] = node;
} else {
struct Node* p = ht->data[index];
while (p->next != NULL) {
p = p->next;
}
p->next = node;
}
}
int search(struct HashTable* ht, int key) {
int index = hash_func(key);
struct Node* p = ht->data[index];
while (p != NULL) {
if (p->key == key) {
return p->value;
}
p = p->next;
}
return -1; // 未找到目标元素
}
int main() {
struct HashTable ht;
for (int i = 0; i < SIZE; i++) {
ht.data[i] = NULL;
}
insert(&ht, 1, 10);
insert(&ht, 11, 20);
insert(&ht, 21, 30);
int value = search(&ht, 11);
if (value == -1) {
printf("未找到目标元素!");
} else {
printf("目标元素的值为:%d", value);
}
return 0;
}
```
以上代码中,`hash_func` 函数实现了哈希函数,`insert` 函数实现了向哈希表中插入元素的操作,`search` 函数实现了在哈希表中查找元素的操作。`main` 函数则测试了该哈希表在插入元素 `{1, 10}`、`{11, 20}`、`{21, 30}` 后查找元素 `11` 的结果。