在C語言中,并沒有直接提供字典這種數(shù)據(jù)結(jié)構(gòu),但可以通過自定義結(jié)構(gòu)體和鏈表來實(shí)現(xiàn)類似字典的功能。以下是一種簡(jiǎn)單的實(shí)現(xiàn)方式:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定義字典節(jié)點(diǎn)結(jié)構(gòu)體
typedef struct Node {
char key[50]; // 鍵
int value; // 值
struct Node* next; // 指向下一個(gè)節(jié)點(diǎn)的指針
} Node;
// 創(chuàng)建新節(jié)點(diǎn)
Node* createNode(char* key, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
strcpy(newNode->key, key);
newNode->value = value;
newNode->next = NULL;
return newNode;
}
// 向字典中插入鍵值對(duì)
void insert(Node** dictionary, char* key, int value) {
Node* newNode = createNode(key, value);
newNode->next = *dictionary;
*dictionary = newNode;
}
// 從字典中查找鍵對(duì)應(yīng)的值
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; // 鍵不存在時(shí)返回-1
}
int main() {
Node* dictionary = NULL; // 初始化字典為空
// 向字典中插入鍵值對(duì)
insert(&dictionary, "apple", 1);
insert(&dictionary, "banana", 2);
insert(&dictionary, "orange", 3);
// 從字典中查找鍵對(duì)應(yīng)的值
int value = find(dictionary, "banana");
if (value != -1) {
printf("Value: %d\n", value);
} else {
printf("Key not found.\n");
}
return 0;
}
這段代碼創(chuàng)建了一個(gè)簡(jiǎn)單的字典,使用鏈表來存儲(chǔ)鍵值對(duì)??梢酝ㄟ^insert函數(shù)向字典中插入鍵值對(duì),通過find函數(shù)從字典中查找鍵對(duì)應(yīng)的值。在主函數(shù)中演示了如何使用這個(gè)字典。