hashtable ref
时间: 2023-09-02 19:13:43 浏览: 53
哈希表(Hashtable)是一种数据结构,它可以将键(Key)与值(Value)进行关联存储。在哈希表中,通过一个哈希函数将键映射到一个索引位置,该索引位置对应的存储位置就是与该键关联的值。
在C语言中,可以使用指针和结构体来实现哈希表。具体实现方式可以参考以下代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 10
// 定义哈希节点结构体
typedef struct Node {
int key;
int value;
struct Node* next;
} Node;
// 创建哈希节点
Node* createNode(int key, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->key = key;
newNode->value = value;
newNode->next = NULL;
return newNode;
}
// 哈希函数
int hashFunction(int key) {
return key % SIZE;
}
// 插入键值对
void insert(Node** hashTable, int key, int value) {
int index = hashFunction(key);
Node* newNode = createNode(key, value);
if (hashTable[index] == NULL) {
hashTable[index] = newNode;
} else {
Node* current = hashTable[index];
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
// 查找键对应的值
int search(Node** hashTable, int key) {
int index = hashFunction(key);
Node* current = hashTable[index];
while (current != NULL) {
if (current->key == key) {
return current->value;
}
current = current->next;
}
return -1; // 未找到
}
int main() {
Node** hashTable = (Node**)malloc(SIZE * sizeof(Node*));
memset(hashTable, 0, SIZE * sizeof(Node*));
// 插入键值对
insert(hashTable, 1, 10);
insert(hashTable, 2, 20);
insert(hashTable, 3, 30);
// 查找键对应的值
int value = search(hashTable, 2);
if (value != -1) {
printf("Found value: %d\n", value);
} else {
printf("Key not found\n");
}
return 0;
}
```
以上代码实现了一个简单的哈希表,其中使用了哈希函数将键映射到索引位置,并通过链表处理哈希冲突(多个键映射到同一个索引位置)。你可以根据需要自行扩展和优化该实现。