#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义链表节点
typedef struct Node {
struct {
int data;
struct {
char str[50];
} *inner;
} info;
struct Node *next;
} Node;
// 创建新节点
Node* createNode(int num, const char *str) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->info.data = num;
newNode->info.inner = (typeof(newNode->info.inner))malloc(sizeof(*newNode->info.inner));
strcpy(newNode->info.inner->str, str);
newNode->next = NULL;
return newNode;
}
// 插入节点到链表头部
void insertNode(Node **head, int num, const char *str) {
Node *newNode = createNode(num, str);
newNode->next = *head;
*head = newNode;
}
// 遍历链表
void traverseList(Node *head) {
Node *current = head;
while (current != NULL) {
printf("Data: %d, String: %s\n", current->info.data, current->info.inner->str);
current = current->next;
}
}
// 释放链表内存
void freeList(Node *head) {
Node *current = head;
Node *nextNode;
while (current != NULL) {
nextNode = current->next;
free(current->info.inner);
free(current);
current = nextNode;
}
}
int main() {
Node *head = NULL;
insertNode(&head, 1, "Hello");
insertNode(&head, 2, "World");
traverseList(head);
freeList(head);
return 0;
}
这样设计的好处
- 数据封装性:通过匿名结构体嵌套,将相关的数据(整型数据和字符数组)封装在节点内部,使代码结构更清晰,外部不需要了解内部具体结构细节。
- 灵活性:可以方便地扩展内部匿名结构体的成员,而不会影响到链表的整体逻辑,例如可以在内层匿名结构体添加更多属性。
内存管理注意事项
- 节点内存释放:在释放链表节点时,不仅要释放节点本身的内存,还要释放内层匿名结构体指针指向的内存,如上述代码
freeList
函数中,先释放current->info.inner
,再释放current
。
- 内存分配检查:在使用
malloc
分配内存后,要检查返回值是否为NULL
,防止内存分配失败导致程序崩溃,上述代码中未做检查是为了简洁,实际应用中应添加。