链地址法查找C语言全部代码
时间: 2023-11-16 16:10:29 浏览: 28
抱歉,我不清楚您具体需要的是什么,但是如果您想了解哈希表中的链地址法,可以查看以下C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义哈希表中链表的节点结构体
typedef struct Node {
char* key;
char* value;
struct Node* next;
} Node;
// 定义哈希表结构体
typedef struct {
int size;
Node** table;
} HashTable;
// 计算字符串的哈希值
int hash(char* key, int size) {
int hash = 0;
for (int i = 0; i < strlen(key); i++) {
hash += key[i];
}
return hash % size;
}
// 创建哈希表
HashTable* createHashTable(int size) {
HashTable* hashtable = (HashTable*)malloc(sizeof(HashTable));
hashtable->size = size;
hashtable->table = (Node**)malloc(sizeof(Node*) * size);
memset(hashtable->table, 0, sizeof(Node*) * size);
return hashtable;
}
// 插入键值对
void put(HashTable* hashtable, char* key, char* value) {
int index = hash(key, hashtable->size);
Node* node = (Node*)malloc(sizeof(Node));
node->key = key;
node->value = value;
node->next = NULL;
if (hashtable->table[index] == NULL) {
hashtable->table[index] = node;
} else {
Node* cur_node = hashtable->table[index];
while (cur_node->next != NULL) {
cur_node = cur_node->next;
}
cur_node->next = node;
}
}
// 根据键查找值
char* get(HashTable* hashtable, char* key) {
int index = hash(key, hashtable->size);
Node* node = hashtable->table[index];
while (node != NULL) {
if (strcmp(node->key, key) == 0) {
return node->value;
}
node = node->next;
}
return NULL;
}
// 销毁哈希表
void destroyHashTable(HashTable* hashtable) {
for (int i = 0; i < hashtable->size; i++) {
Node* node = hashtable->table[i];
while (node != NULL) {
Node* next_node = node->next;
free(node);
node = next_node;
}
}
free(hashtable->table);
free(hashtable);
}
// 测试
int main() {
HashTable* hashtable = createHashTable(5);
put(hashtable, "apple", "red");
put(hashtable, "banana", "yellow");
put(hashtable, "grape", "purple");
put(hashtable, "orange", "orange");
put(hashtable, "watermelon", "green");
printf("The color of apple is %s\n", get(hashtable, "apple"));
printf("The color of banana is %s\n", get(hashtable, "banana"));
printf("The color of grape is %s\n", get(hashtable, "grape"));
printf("The color of orange is %s\n", get(hashtable, "orange"));
printf("The color of watermelon is %s\n", get(hashtable, "watermelon"));
destroyHashTable(hashtable);
return 0;
}
```
以上是一个简单的基于链地址法的哈希表实现,其中包括了创建哈希表、插入键值对、根据键查找值以及销毁哈希表等基本操作。