Kye*_*vid 1 c linked-list pass-by-reference
所以我在我的链表代码中使用了按引用传递,但问题是它没有打印,我该如何解决这个问题?
我的代码:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int x;
struct node *next;
};
void add(struct node **root, int x)
{
struct node *conductor;
if(root==NULL)
{
(*root)=malloc(sizeof(struct node));
(*root)->x=x;
(*root)->next=NULL ;
}
else
{
conductor = *root;
while(conductor->next!=NULL)
{
conductor = conductor -> next;
}
conductor->next=malloc(sizeof(struct node));
conductor->next->x=x;
conductor->next->next=NULL;
}
}
void display(struct node *root)
{
struct node *conductor;
conductor=root;
while(conductor!=NULL)
{
printf("%d",conductor->x);
conductor = conductor ->next;
}
}
int main()
{
struct node *root;
root=NULL;
add(&root,5);
add(&root,4);
display(root);
free(root);
system("pause");
}
Run Code Online (Sandbox Code Playgroud)
更好的形式 http://codepad.org/CPdUvK0x
不是我程序中的所有节点都是链接的吗?
void add(struct node **root, int x)
{
struct node *conductor;
if(root==NULL)
Run Code Online (Sandbox Code Playgroud)
那应该是如果 (*root == NULL)
因为你打电话add(&root... root永远不会是NULL。