繁体   English   中英

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

[英]I cannot traverse through my linked list, after creating an array of nodes

我为链表创建了一个节点数组,但是当我尝试遍历以打印链表时,我崩溃了。 当我不创建节点数组时,遍历效果很好,因此我认为这是我的问题。

   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是一个非常简单的前端插入算法。 谁能看到我哪里出问题了?

谁能看到我哪里出问题了?

发布的代码表明您已经创建了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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM