用c语言创建一个哈西表
时间: 2023-07-16 19:12:34 浏览: 114
好的,下面是一个简单的使用C语言创建哈希表的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define TABLE_SIZE 100
typedef struct node {
int key;
int value;
struct node* next;
} node;
node* hash_table[TABLE_SIZE];
int hash_function(int key) {
return key % TABLE_SIZE;
}
void insert(int key, int value) {
int index = hash_function(key);
node* new_node = (node*)malloc(sizeof(node));
new_node->key = key;
new_node->value = value;
new_node->next = NULL;
if (hash_table[index] == NULL) {
hash_table[index] = new_node;
} else {
node* current = hash_table[index];
while (current->next != NULL) {
current = current->next;
}
current->next = new_node;
}
}
int search(int key) {
int index = hash_function(key);
node* current = hash_table[index];
while (current != NULL) {
if (current->key == key) {
return current->value;
}
current = current->next;
}
return -1;
}
void delete(int key) {
int index = hash_function(key);
node* current = hash_table[index];
node* previous = NULL;
while (current != NULL) {
if (current->key == key) {
if (previous == NULL) {
hash_table[index] = current->next;
} else {
previous->next = current->next;
}
free(current);
return;
}
previous = current;
current = current->next;
}
}
int main() {
insert(1, 10);
insert(2, 20);
insert(3, 30);
printf("Value for key 1: %d\n", search(1));
printf("Value for key 2: %d\n", search(2));
printf("Value for key 3: %d\n", search(3));
delete(2);
printf("Value for key 2 after deletion: %d\n", search(2));
return 0;
}
```
在这个示例中,我们使用一个数组来存储哈希表,每个元素都是一个指向节点的指针。节点包含键、值和指向下一个节点的指针。我们使用模运算来计算键的哈希值,然后将节点插入到哈希表中。在搜索时,我们计算键的哈希值,并遍历链表来查找键的值。在删除时,我们首先搜索键的位置,然后重新链接链表。
阅读全文