C语言如何创建字典

   2025-02-15 3050
核心提示:在C语言中,并没有直接提供字典这种数据结构,但可以通过自定义结构体和链表来实现类似字典的功能。以下是一种简单的实现方式:#

在C语言中,并没有直接提供字典这种数据结构,但可以通过自定义结构体和链表来实现类似字典的功能。以下是一种简单的实现方式:

#include <stdio.h>#include <stdlib.h>#include <string.h>// 定义字典节点结构体typedef struct Node {    char key[50];  // 键    int value;     // 值    struct Node* next;  // 指向下一个节点的指针} Node;// 创建新节点Node* createNode(char* key, int value) {    Node* newNode = (Node*)malloc(sizeof(Node));    strcpy(newNode->key, key);    newNode->value = value;    newNode->next = NULL;    return newNode;}// 向字典中插入键值对void insert(Node** dictionary, char* key, int value) {    Node* newNode = createNode(key, value);    newNode->next = *dictionary;    *dictionary = newNode;}// 从字典中查找键对应的值int find(Node* dictionary, char* key) {    Node* cur = dictionary;    while (cur != NULL) {        if (strcmp(cur->key, key) == 0) {            return cur->value;        }        cur = cur->next;    }    return -1;  // 键不存在时返回-1}int main() {    Node* dictionary = NULL;  // 初始化字典为空    // 向字典中插入键值对    insert(&dictionary, "apple", 1);    insert(&dictionary, "banana", 2);    insert(&dictionary, "orange", 3);    // 从字典中查找键对应的值    int value = find(dictionary, "banana");    if (value != -1) {        printf("Value: %d\n", value);    } else {        printf("Key not found.\n");    }    return 0;}

这段代码创建了一个简单的字典,使用链表来存储键值对。可以通过insert函数向字典中插入键值对,通过find函数从字典中查找键对应的值。在主函数中演示了如何使用这个字典。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言