简体   繁体   English

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

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

I've created an array of nodes for a linked list however when I attempt to traverse to print my linked list I crash. 我为链表创建了一个节点数组,但是当我尝试遍历以打印链表时,我崩溃了。 My traversal works a treat when I do not create an array of nodes so I figure this snippit of code is my problem. 当我不创建节点数组时,遍历效果很好,因此我认为这是我的问题。

   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;

Clearly I've done something wrong, insert_node is a really simple insert at front algorithm by the way. 显然,我做错了,顺便说一下,insert_node是一个非常简单的前端插入算法。 Can anyone see where I've gone wrong? 谁能看到我哪里出问题了?

Can anyone see where I've gone wrong? 谁能看到我哪里出问题了?

The posted code shows that you have created 100 pointers and assigned memory to them from the value returned by malloc . 发布的代码表明您已经创建了100个指针,并根据malloc返回的值为其分配了内存。 However, you haven't linked them up together to form a linked list. 但是,您尚未将它们链接在一起以形成链接列表。

Perhaps you meant to use: 也许您打算使用:

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];
}

That will make newNodes[0] the head of the linked list. 这将使newNodes[0]成为链接列表的头部。

PS PS

Using a typedef called Node that is a pointer is very confusing, at least to me. 至少对于我来说,使用一个称为Nodetypedef作为指针非常令人困惑。 I would recommend using: 我建议使用:

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