MST

星途 面试题库

面试题:C语言匿名结构体在链表嵌套场景的应用

请设计一个链表结构,链表节点内部包含一个匿名结构体,匿名结构体中又嵌套另一个匿名结构体,外层匿名结构体包含一个整型数据和一个指向内层匿名结构体的指针,内层匿名结构体包含一个字符数组。编写代码实现链表的创建、节点插入与遍历功能,并阐述这样设计的好处以及在内存管理上需要注意什么。
29.7万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#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;
}

这样设计的好处

  1. 数据封装性:通过匿名结构体嵌套,将相关的数据(整型数据和字符数组)封装在节点内部,使代码结构更清晰,外部不需要了解内部具体结构细节。
  2. 灵活性:可以方便地扩展内部匿名结构体的成员,而不会影响到链表的整体逻辑,例如可以在内层匿名结构体添加更多属性。

内存管理注意事项

  1. 节点内存释放:在释放链表节点时,不仅要释放节点本身的内存,还要释放内层匿名结构体指针指向的内存,如上述代码freeList函数中,先释放current->info.inner,再释放current
  2. 内存分配检查:在使用malloc分配内存后,要检查返回值是否为NULL,防止内存分配失败导致程序崩溃,上述代码中未做检查是为了简洁,实际应用中应添加。