C语言如何在链表节点结构体中存储包含多字段的自定义结构体
实现方案
- 第一步:自定义业务数据结构体,存储source、destination、time三个属性
你可以根据实际需求调整三个字段的类型,示例中我们用字符数组存储地点、int类型存储时间戳:
typedef struct { char source[32]; // 出发地,可调整数组长度或改为char*类型存储动态长度字符串 char destination[32]; // 目的地,可调整数组长度或改为char*类型存储动态长度字符串 int time; // 时间,可替换为time_t等其他时间类型 } TransportInfo;
- 第二步:修改原链表节点结构体,替换char类型的data为自定义结构体
typedef struct Node { TransportInfo data; // 将原char data替换为自定义的TransportInfo类型 struct Node *next; } Node;
- 第三步:修改头插函数
push_front的入参与赋值逻辑,适配新的结构体规则
// 入参从原char类型改为自定义的TransportInfo结构体类型 int push_front( Node **head, TransportInfo data ) { Node *new_node = malloc( sizeof( Node ) ); int success = new_node != NULL; if ( success ) { new_node->data = data; // 结构体可直接赋值拷贝 new_node->next = *head; *head = new_node; } return success; }
使用示例
#include <stdio.h> #include <stdlib.h> #include <string.h> // 此处插入上面定义的TransportInfo、Node结构体和push_front函数 int main() { Node *head = NULL; // 构造业务数据 TransportInfo info; strcpy(info.source, "广州"); strcpy(info.destination, "深圳"); info.time = 1701234567; // 插入节点 push_front(&head, info); // 读取节点属性 printf("出发地:%s,目的地:%s,时间戳:%d\n", head->data.source, head->data.destination, head->data.time); // 业务逻辑结束后请自行遍历释放链表内存,避免内存泄漏 return 0; }
注意:如果source、destination字段使用
char*类型存储动态长度字符串,不要直接对指针赋值,需要单独申请内存拷贝字符串内容,避免原内存被释放后出现野指针问题。
内容的提问来源于stack exchange,提问作者wajaap
相关产品推荐
相关产品推荐

