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

C语言实现同类型Node构成的父节点环形双向子节点链表的问询

问题核心

你的代码中定义了两套独立的双向链表指针,但插入逻辑没有对应上指针的用途,导致运行异常:

  • previous/next:子节点在父节点的子链表中的前后串联指针
  • nodes_previous/nodes_next:父节点标记自身子链表头尾的哨兵指针
    你在插入新节点时仅更新了子节点的previous/next和父节点的nodes_previous,从未修改过父节点的nodes_next,导致正向遍历从parent.nodes_next启动时,该指针始终指向父节点自身,循环直接终止。

修复方案

在原有设计基础上补充第一个子节点插入时的nodes_next更新逻辑即可,修改后的完整代码如下:

#include <stdio.h>
#include <stdlib.h>

typedef struct Node Node;

struct Node {
    Node * parent;
    Node * nodes_previous;
    Node * nodes_next;
    Node * previous;
    Node * next;
    int value;
};

Node *
Node_create(Node * const parent, int const value) {
    Node * const node = malloc(sizeof(Node));
    *node = (Node) {
        .parent = parent,
        .nodes_previous = node,
        .nodes_next = node,
        .previous = parent->nodes_previous,
        .next = parent,
        .value = value,
    };
    parent->nodes_previous->next = node;
    parent->nodes_previous = node;
    // 新增:首次插入子节点时更新父节点的子链表头指针
    if (parent->nodes_next == parent) {
        parent->nodes_next = node;
    }
    return node;
}

int
main() {

    Node parent = {
        .nodes_previous = &parent,
        .nodes_next = &parent,
    };

    (void)Node_create(&parent, 1);
    (void)Node_create(&parent, 2);
    (void)Node_create(&parent, 3);

    // 正向遍历 输出1、2、3
    for (Node * cur = parent.nodes_next; cur != &parent; cur = cur->next) {
        printf("Value: %d\n", cur->value);
    }

    // 反向遍历 输出3、2、1
    for (Node * cur = parent.nodes_previous; cur != &parent; cur = cur->previous) {
        printf("Value: %d\n", cur->value);
    }

    return 0;
}

拓展优化建议

如果不需要同时维护两套链表,你可以直接删除冗余的nodes_previous/nodes_next指针,让父节点直接作为子链表的哨兵节点,所有节点共用一套previous/next指针,代码逻辑会更简洁不易出错。


内容的提问来源于stack exchange,提问作者João Pires

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:21:01