C语言哈希表基本操作请用代码展示
时间: 2023-05-11 18:02:38 浏览: 121
haxi.rar_C语言 哈希表_哈希表
好的,以下是C语言哈希表的基本操作代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 100
typedef struct Node {
char* key;
char* value;
struct Node* next;
} Node;
Node* table[TABLE_SIZE];
unsigned int hash(char* key) {
unsigned int hash = 0;
for (int i = 0; i < strlen(key); i++) {
hash = hash * 31 + key[i];
}
return hash % TABLE_SIZE;
}
void put(char* key, char* value) {
unsigned int index = hash(key);
Node* node = table[index];
while (node != NULL) {
if (strcmp(node->key, key) == 0) {
node->value = value;
return;
}
node = node->next;
}
node = (Node*)malloc(sizeof(Node));
node->key = key;
node->value = value;
node->next = table[index];
table[index] = node;
}
char* get(char* key) {
unsigned int index = hash(key);
Node* node = table[index];
while (node != NULL) {
if (strcmp(node->key, key) == 0) {
return node->value;
}
node = node->next;
}
return NULL;
}
void remove_key(char* key) {
unsigned int index = hash(key);
Node* node = table[index];
Node* prev = NULL;
while (node != NULL) {
if (strcmp(node->key, key) == 0) {
if (prev == NULL) {
table[index] = node->next;
} else {
prev->next = node->next;
}
free(node);
return;
}
prev = node;
node = node->next;
}
}
void print_table() {
for (int i = 0; i < TABLE_SIZE; i++) {
printf("%d: ", i);
Node* node = table[i];
while (node != NULL) {
printf("(%s, %s) ", node->key, node->value);
node = node->next;
}
printf("\n");
}
}
int main() {
put("apple", "red");
put("banana", "yellow");
put("orange", "orange");
print_table();
printf("apple: %s\n", get("apple"));
printf("banana: %s\n", get("banana"));
printf("orange: %s\n", get("orange"));
remove_key("banana");
print_table();
return 0;
}
```
这段代码实现了哈希表的基本操作,包括插入、查找、删除和打印哈希表。其中,哈希函数使用了简单的字符串哈希算法,冲突解决采用了链表法。
阅读全文