c语言实现哈希表(链地址法)
时间: 2023-08-04 08:03:21 浏览: 138
好的,以下是C语言实现哈希表(链地址法)的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_TABLE_SIZE 100
// 定义哈希表中的节点
typedef struct Node {
char* key;
char* value;
struct Node* next;
} Node;
// 初始化哈希表
void initHashTable(Node** hashTable) {
int i;
for (i = 0; i < MAX_TABLE_SIZE; i++) {
hashTable[i] = NULL;
}
}
// 计算哈希值
int hash(char* key) {
int hashValue = 0;
while (*key) {
hashValue = (hashValue << 5) + *key++;
}
return hashValue % MAX_TABLE_SIZE;
}
// 插入节点
void insertNode(Node** hashTable, char* key, char* value) {
int hashValue = hash(key);
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->key = strdup(key);
newNode->value = strdup(value);
newNode->next = hashTable[hashValue];
hashTable[hashValue] = newNode;
}
// 查找节点
char* findValueByKey(Node** hashTable, char* key) {
int hashValue = hash(key);
Node* node = hashTable[hashValue];
while (node != NULL) {
if (strcmp(node->key, key) == 0) {
return node->value;
}
node = node->next;
}
return NULL;
}
// 删除节点
void deleteNode(Node** hashTable, char* key) {
int hashValue = hash(key);
Node* node = hashTable[hashValue];
Node* prevNode = NULL;
while (node != NULL) {
if (strcmp(node->key, key) == 0) {
if (prevNode == NULL) {
hashTable[hashValue] = node->next;
} else {
prevNode->next = node->next;
}
free(node->key);
free(node->value);
free(node);
return;
}
prevNode = node;
node = node->next;
}
}
// 打印哈希表
void printHashTable(Node** hashTable) {
int i;
printf("----- Hash Table -----\n");
for (i = 0; i < MAX_TABLE_SIZE; i++) {
Node* node = hashTable[i];
printf("[%d]: ", i);
while (node != NULL) {
printf("(%s, %s) ", node->key, node->value);
node = node->next;
}
printf("\n");
}
printf("----------------------\n");
}
// 主函数
int main() {
Node* hashTable[MAX_TABLE_SIZE];
initHashTable(hashTable);
// 插入节点
insertNode(hashTable, "apple", "red");
insertNode(hashTable, "banana", "yellow");
insertNode(hashTable, "grape", "purple");
insertNode(hashTable, "orange", "orange");
insertNode(hashTable, "watermelon", "green");
// 打印哈希表
printHashTable(hashTable);
// 查找节点
char* value = findValueByKey(hashTable, "banana");
if (value != NULL) {
printf("The value of banana is %s\n", value);
} else {
printf("Cannot find the node\n");
}
// 删除节点
deleteNode(hashTable, "orange");
// 打印哈希表
printHashTable(hashTable);
return 0;
}
```
以上就是C语言实现哈希表(链地址法)的代码示例,其中包括了插入节点、查找节点、删除节点和打印哈希表等操作。
阅读全文