You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何访问嵌套链表结构中的内部链表并实现打印?

访问嵌套链表内部path的实现方法

别担心,咱们一步步拆解这个嵌套链表的访问逻辑,其实很简单。先把你定义的结构再明确下,方便后续讲解:

struct path { 
    int node; 
    struct path *next; 
};
struct path_list { 
    struct path *path; 
    int path_size; 
    struct path_list *next; 
};

// 你已定义的头尾指针
struct path_list *listHead = NULL;
struct path_list *listTail = NULL;

核心思路

每个path_list节点都包含一个指向内部path链表的指针path,所以我们只需要先遍历外层的path_list链表,再对每个外层节点,二次遍历它内部的path链表,就能访问到所有node元素了。

具体实现代码

这里给你写一个完整的示例函数,用来打印所有路径里的节点值,你可以参考这个逻辑做其他操作:

#include <stdio.h>

void print_all_paths(struct path_list *head) {
    // 遍历外层 path_list 链表
    struct path_list *current_pl = head;
    int group_index = 0; // 标记当前是第几个路径组,方便输出区分

    while (current_pl != NULL) {
        printf("第 %d 个路径组(size: %d)的节点:", group_index++, current_pl->path_size);
        
        // 遍历当前路径组内部的 path 链表
        struct path *current_p = current_pl->path;
        while (current_p != NULL) {
            // 访问内部链表的 node 成员
            printf("%d ", current_p->node);
            // 移动内部链表指针到下一个节点
            current_p = current_p->next;
        }
        printf("\n");

        // 移动外层链表指针到下一个路径组
        current_pl = current_pl->next;
    }
}

// 调用示例(假设你已经构建好链表)
// print_all_paths(listHead);

代码解释

  1. 外层遍历:用current_pl指针从listHead开始,逐个遍历每个path_list节点,直到指针为NULL(链表结束)。
  2. 内层遍历:对每个current_pl节点,取出它的path指针作为内部链表的头,用current_p指针逐个遍历内部的path节点,通过current_p->node就能拿到每个节点的值。
  3. 空指针防护:两个while循环都判断指针不为NULL,避免访问空指针导致程序崩溃。

额外提示

如果你的链表是用malloc动态分配的内存,记得在使用完后逐层释放内存,避免内存泄漏哦。

内容的提问来源于stack exchange,提问作者Saeed Rahmani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:47:14