我被告知,这将无法正确地将节点添加到列表中,但我已经测试它,它似乎工作。任何人都可以让我知道这段代码中的错误吗?将元素添加到c中的列表开头的代码 - 错误是什么?
struct node {
int num;
struct node* next;
};
void add_first(struct node* head, struct node* new_node) {
new_node->next = head;
head = new_node;
}
我试图回答的具体问题是:
一)此功能将无法得到期望的结果(即,添加节点)。什么是问题,什么时候发生?
为了尝试找到问题,我创建了四个节点,在它们上使用add_first函数,然后显示结果。不过,我似乎得到了正确的输出结果。这是我整个编写的程序,不包括上述功能:
void display(struct node* head) {
printf("%d ", head->num);
if(head->next == NULL) {
return;
}
display(head->next);
}
int main() {
struct node* n1;
struct node* n2;
struct node* n3;
n1 = (struct node*)malloc(sizeof(struct node*));
n2 = (struct node*)malloc(sizeof(struct node*));
n3 = (struct node*)malloc(sizeof(struct node*));
n1->num = 1;
n2->num = 2;
n3->num = 3;
add_first(n1, n2);
add_first(n2, n3);
display(n3);
return 0;
}
我得到的输出是:
这似乎是正确的。所以,如果我得到正确的输出,为什么函数不能给出预期的结果?我没有看到它的问题。
majar问题是,你不能更新调用者的节点。尝试更改API以使其更像'n1 = add_first(n1,n2);'(返回头部)并且其他问题是'sizeof(struct node *)' - >'sizeof(struct node)'并且'next'没有被初始化。 E.g'n1-> num = 1;' - >'n1-> num = 1; n1-> next = NULL;' – BLUEPIXY