gpt4 book ai didi

c - 创建节点数组后,我无法遍历链接列表

转载 作者:行者123 更新时间:2023-11-30 15:20:42 25 4
gpt4 key购买 nike

我已经为链表创建了一个节点数组,但是当我尝试遍历以打印我的链表时,我崩溃了。当我不创建节点数组时,我的遍历很有效,所以我认为这段代码是我的问题。

   typedef struct node {
book data;
struct node *next;
} *Node;

Node newNodes[100];
int i = 0;
for (i=0; i<n; i++)
{
newNodes[i] = (Node)malloc(sizeof(struct node));
newNodes[i]->next = NULL;
newNodes[i]->data.time = NULL;
newNodes[i]->data.format = NULL;
}


//return struct that holds the array;

显然我做错了什么,顺便说一句,insert_node 是一个非常简单的前端插入算法。谁能看出我哪里出了问题吗?

最佳答案

Can anyone see where I've gone wrong?

发布的代码显示您已经创建了 100 个指针,并根据 malloc 返回的值为它们分配了内存。但是,您还没有将它们链接在一起形成链接列表。

也许您想使用:

for (i=0; i<n; i++) 
{
newNodes[i] = (Node)malloc(sizeof(struct node));
newNodes[i]->next = NULL;
newNodes[i]->data.time = NULL;
newNodes[i]->data.format = NULL;
}

// Make the links between the nodes.
for (i=0; i<n-1; i++)
{
newNodes[i]->next = newNodes[i+1];
}

这将使 newNodes[0] 成为链表的头部。

PS

使用名为 Nodetypedef 作为指针非常令人困惑,至少对我来说是这样。我建议使用:

typedef struct node {
book data;
struct node *next;
} Node;

typedef Node* NodePtr;

关于c - 创建节点数组后,我无法遍历链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29910705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com