c - 递归调用c创建链接列表
问题描述
我是c新手,所以任何帮助都将不胜感激。我需要从链表中打印 10 个数字(现在哪个数字都没有关系)我相信我的代码会打印 9、8、7...0。例如。链表将是包含其他变量的结构(结构数据)的一部分(暂时不重要)
//linked list
struct listOfNodes {
struct node *root;
};
//list of parameters to send to the function to print nodes
struct data {
struct listOfNodes *list;
int total;
};
我需要将结构(结构数据)作为递归函数(addNode)的参数发送。在这个递归函数中,我需要在链表中添加一个新节点并递归调用 10 次为链表创建更多节点,然后我需要打印链表。到目前为止我有以下代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//node
struct node {
int value;
struct node *next;
};
//linked list
struct listOfNodes {
struct node *root;
};
//list of parameters to send to the function to print nodes
struct data {
struct listOfNodes *list;
int total;
};
void printNode(struct listOfNodes *list) {
struct node *n = list->root;
while(n!=NULL){
printf("%d\n",n->value);
n=n->next;
}
}
void addNode(void* d){ //parameter needs to be a void*
struct data *o = (struct data *)d ;
if(o->total<10) {
//create new node
struct node *n = malloc(sizeof(struct node));
n->value = o->total;
n->next = NULL;
o->total = o->total + 1;
if(o->list->root == NULL)
{
o->list->root = n;
}
else {
n->next = o->list->root->next;
o->list->root->next = n;
}
addNode(d);
}
}
int main() {
struct data *d= malloc(sizeof(struct data *));
d->total=0;
d->list=NULL;
addNode(d); //add recursively 10 times
if(d->list!=NULL) printNode(d->list);
return 0;
}
但是我遇到了分段错误(核心转储)。你能帮我么?
解决方案
在您的主程序中,您将列表添加为 NULL。但是在您的 addNode 中,您只检查 list->root 是否为 NULL。发生的事情是什么时候
if(o->list->root == NULL)
{
o->list->root = n;
}
当 list 为 NULL 时正在访问 list->root。您取消引用 NULL 指针和段错误。
你可能需要
struct listOfNodes *variable=malloc(sizeof(struct listOfNodes));
d->list=variable;