6. [问答题] <key,value> 结构是常用的数据储存结构,如<张三,19岁> <李四,18岁>,请编程实现<key,value>存储程序模块,向外提供创建和增删改查接口功能。用c语言简单的描述
时间: 2024-09-13 15:07:49 浏览: 99
在C语言中实现一个简单的键值对(<key, value>)存储程序模块,我们可以使用结构体来定义键值对,并用链表来管理这些结构体,以实现创建、增、删、改、查的基本操作。以下是一个简化的示例:
首先定义一个键值对结构体:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义键值对结构体
typedef struct KeyValueNode {
char *key;
char *value;
struct KeyValueNode *next;
} KeyValueNode;
```
然后创建一个简单的链表结构来管理这些键值对:
```c
// 创建新的键值对节点
KeyValueNode* createKeyValueNode(const char *key, const char *value) {
KeyValueNode *node = (KeyValueNode*)malloc(sizeof(KeyValueNode));
if (!node) return NULL;
node->key = strdup(key); // 复制key字符串
node->value = strdup(value); // 复制value字符串
node->next = NULL;
return node;
}
// 在链表尾部添加键值对
void addKeyValueNode(KeyValueNode **head, const char *key, const char *value) {
KeyValueNode *newNode = createKeyValueNode(key, value);
if (!newNode) return;
if (*head == NULL) {
*head = newNode;
} else {
KeyValueNode *current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
// 查找键值对
KeyValueNode* findKeyValueNode(KeyValueNode *head, const char *key) {
KeyValueNode *current = head;
while (current != NULL) {
if (strcmp(current->key, key) == 0) {
return current;
}
current = current->next;
}
return NULL;
}
// 删除键值对
void deleteKeyValueNode(KeyValueNode **head, const char *key) {
KeyValueNode *current = *head;
KeyValueNode *previous = NULL;
while (current != NULL) {
if (strcmp(current->key, key) == 0) {
if (previous == NULL) {
*head = current->next;
} else {
previous->next = current->next;
}
free(current->key);
free(current->value);
free(current);
return;
}
previous = current;
current = current->next;
}
}
// 更新键值对
void updateKeyValueNode(KeyValueNode *node, const char *value) {
if (node != NULL) {
free(node->value);
node->value = strdup(value);
}
}
// 清理整个键值对链表
void freeKeyValueList(KeyValueNode **head) {
KeyValueNode *current = *head;
KeyValueNode *next = NULL;
while (current != NULL) {
next = current->next;
free(current->key);
free(current->value);
free(current);
current = next;
}
*head = NULL;
}
// 使用示例
int main() {
KeyValueNode *head = NULL;
addKeyValueNode(&head, "张三", "19岁");
addKeyValueNode(&head, "李四", "18岁");
KeyValueNode *found = findKeyValueNode(head, "张三");
if (found != NULL) {
printf("找到键值对: %s -> %s\n", found->key, found->value);
}
updateKeyValueNode(found, "20岁");
printf("更新后的键值对: %s -> %s\n", found->key, found->value);
deleteKeyValueNode(&head, "李四");
printf("删除键值对后列表中的内容:\n");
found = findKeyValueNode(head, "李四");
if (found == NULL) {
printf("未找到李四。\n");
}
freeKeyValueList(&head);
return 0;
}
```
这段代码展示了如何使用C语言来创建一个简单的键值对存储模块。它包含了创建新节点、添加到链表、查找节点、更新节点值、删除节点以及释放整个链表的功能。
阅读全文