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

我需要将结构(structdata(作为递归函数(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("%dn",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;
}

但我有分段错误(核心转储(。你能帮帮我吗?

在主程序中,您将list添加为NULL。但在您的addNode中,您只检查列表是否->根为NULL。当

if(o->list->root == NULL)
{
o->list->root = n;
}

正在访问列表->当列表为NULL时为root。您取消引用NULL指针和segfault。

你可能需要

struct listOfNodes *variable=malloc(sizeof(struct listOfNodes));
d->list=variable;

更改在注释中描述

#include <stdio.h>
// #include <string.h>  // <------- 4  not needed.
#include <stdlib.h>
struct node {//node
int value;
struct node *next;
};
struct listOfNodes {//linked list
struct node *root;
};
struct data {//list of parameters to send to the function to print nodes
struct listOfNodes *list;
int total;
};
void printNode(struct listOfNodes *list) {
struct node *n = list->root;
while(n!=NULL){
printf("%dn",n->value);
n=n->next;
}
}
void addNode(struct data * d){  // <------- 3 no need to be void *  so o replaced by d
if(d->total<10) {
//create new node
struct node *n = malloc(sizeof(struct node));
n->value = d->total;
n->next = NULL;
d->total = d->total + 1;
if(d->list->root == NULL)
{
d->list->root = n;
}
else {
n->next = d->list->root->next;
d->list->root->next = n;
}
addNode(d);
}
}
int main() {
struct data *d= malloc(sizeof(struct data));  // <---- 1 allocate data size not pointer size.
d->total=0;
d->list = malloc(sizeof(struct listOfNodes)); // <---- 2 alocate list !
d->list->root = NULL;                         // <---- 2 init root.

addNode(d); //add recursively 10 times
if(d->list!=NULL) printNode(d->list);
return 0;
}

相关内容

  • 没有找到相关文章

最新更新