温馨提示×

C语言如何创建字典

小亿
155
2023-11-22 15:51:36
栏目: 编程语言

在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函数从字典中查找键对应的值。在主函数中演示了如何使用这个字典。

0