通过链接列表使用引用传递
因此,我在链接列表代码上使用了引用传递,但问题是它没有打印,那么我该如何解决这个问题呢?
我的代码:
#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");
}
形式更好 http://codepad.org/CPdUvK0x
我的程序里不是所有节点都链接了吗?
So I've use pass by reference on my linked list code but the problem is it's not printing soo how do I actually fix this?
my code:
#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");
}
In better form
http://codepad.org/CPdUvK0x
Isn't it all nodes in my program are linked?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
应该是 if
(*root == NULL)
因为你调用
add(&root...
root
永远不会是 NULL 。That should be if
(*root == NULL)
Since you're calling
add(&root...
root
will never be NULL.检查:
应该
是通过地址传递
root
。此外,您还执行 free(root) 来释放整个列表,这是不正确的,因为它仅释放第一个节点,并使其他节点无法访问,从而导致内存泄漏。要解决此问题,您需要一一释放节点,如下所示:
The check:
should be
as
root
is being passed by address.Also you do
free(root)
to free the entire list which is incorrect as it frees only the first node and makes the other nodes unreachable causing memory leak. To fix this you need to free the nodes one by one as:问题出在
add()
中:这个测试是错误的:通过引用传递的 root 永远不会是 NULL(在 main 中看到,它包含根节点的地址) 。您应该正确测试 rrot 节点是否为 NULL:
我还要补充一点,您释放为 ist 分配的内存的方式是错误的:
只会释放根节点,但会泄漏子节点...
the problem is in
add()
:this test is wrong: root being passed by reference is never NULL (see in the main, it contains the address of the root node). you should correctly test if the rrot node is NULL:
i would also add that your way of freeing the memory allocated for the ist is wrong:
will only free the root node, but will leak the child nodes...