C语言哈斯图代码
时间: 2023-07-09 07:25:05 浏览: 157
偏序关系的哈斯图求解
5星 · 资源好评率100%
以下是一个简单的C语言哈希表代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 1000
typedef struct Node {
char* key;
int value;
struct Node* next;
} Node;
typedef struct HashTable {
Node* nodes[TABLE_SIZE];
} HashTable;
int hash(char* key) {
int hash = 0;
for (int i = 0; i < strlen(key); ++i) {
hash = (hash * 31 + key[i]) % TABLE_SIZE;
}
return hash;
}
Node* create_node(char* key, int value) {
Node* node = (Node*)malloc(sizeof(Node));
node->key = key;
node->value = value;
node->next = NULL;
return node;
}
void insert(HashTable* table, char* key, int value) {
int index = hash(key);
Node* node = table->nodes[index];
while (node != NULL) {
if (strcmp(node->key, key) == 0) {
node->value = value;
return;
}
node = node->next;
}
Node* new_node = create_node(key, value);
new_node->next = table->nodes[index];
table->nodes[index] = new_node;
}
int lookup(HashTable* table, char* key) {
int index = hash(key);
Node* node = table->nodes[index];
while (node != NULL) {
if (strcmp(node->key, key) == 0) {
return node->value;
}
node = node->next;
}
return -1;
}
int main() {
HashTable* table = (HashTable*)malloc(sizeof(HashTable));
insert(table, "apple", 1);
insert(table, "banana", 2);
insert(table, "cherry", 3);
printf("%d\n", lookup(table, "apple"));
printf("%d\n", lookup(table, "banana"));
printf("%d\n", lookup(table, "cherry"));
printf("%d\n", lookup(table, "orange"));
return 0;
}
```
在该示例中,哈希表使用链表解决冲突。可以看到,哈希函数通过将键的字符转换为整数,然后使用取模运算将其映射到哈希表的索引。在插入和查找时,将使用哈希函数计算键的哈希值,并使用该值来访问哈希表中的节点。如果发生冲突,则使用链表解决冲突。
阅读全文