作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已经为链表创建了一个节点数组,但是当我尝试遍历以打印我的链表时,我崩溃了。当我不创建节点数组时,我的遍历很有效,所以我认为这段代码是我的问题。
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
使用名为 Node
的 typedef
作为指针非常令人困惑,至少对我来说是这样。我建议使用:
typedef struct node {
book data;
struct node *next;
} Node;
typedef Node* NodePtr;
关于c - 创建节点数组后,我无法遍历链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29910705/
我是一名优秀的程序员,十分优秀!