I've just tried to implement a recursive linked list append in C, and for some reason l keeps being NULL no matter what I do, even though I malloc when encountering a NULL value.
The following code prints nothing. Any ideas?
#include <stdlib.h>
#include <stdio.h>
typedef struct node {
unsigned v;
struct node* next;
} node;
void insert(unsigned x, node* l) {
if (l == NULL){
node* new_node = (node*)malloc(sizeof(node));
new_node->v = x;
new_node->next = NULL;
l = new_node;
}
else {
insert(x, l->next);
}
}
void print(node *l) {
if (l == NULL) return;
printf("%d\n", l->v);
print(l->next);
}
int main(){
node* l = NULL;
insert(1, l);
insert(2, l);
print(l);
return 0;
}
Help much appreciated.
EDIT: Even if I initialize it, it's still the same.
答案 0 :(得分:0)
First off, you're passing l to your function by value so you won't see any changes made to it. Currently, when you set l to new_node, you only change the local value of l in the method insert. You may want to modify your function to return l and set l in your main to the return value of this function.
node *insert(int x, node *l){
//.... your method
return l;
}
In main:
node *l = NULL;
l = insert(1, l);
l = insert(2, l);
Second, your recursive call will not append nodes to your LL for the same reason. Change that call to this:
l->next = insert(x, l);
答案 1 :(得分:0)
#include <stdlib.h>
#include <stdio.h>
typedef struct node {
unsigned v;
struct node* next;
} node;
node* insert(unsigned x, node** ll) {
if (*ll == NULL){
*ll = (node*)malloc(sizeof(node));
(*ll)->v = x;
(*ll)->next = NULL;
}
else {
insert(x, &(*ll)->next);
}
}
void print(node *l) {if (l == NULL) return;
printf("%d\n", l->v);
print(l->next);
}
int main(){
node* l = NULL;
insert(1, &l);
insert(2, &l);
print(l);
return 0;
}
编译没有gcc没有开关
输出: 1 2