因此,我在链接列表代码上使用了pass引用,但问题是它不是打印soo,我如何才能真正解决这个问题?
我的代码:
#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
难道不是我程序中的所有节点都是链接的吗?
发布于 2011-03-26 13:00:07
void add(struct node **root, int x)
{
struct node *conductor;
if(root==NULL)那应该是如果(*root == NULL)
由于您正在调用add(&root...,所以root永远不会为空。
发布于 2011-03-26 13:00:27
支票:
if(root==NULL)应该是
if(*root==NULL)因为root是通过地址传递的。
此外,您还可以使用free(root)来释放整个列表,这是不正确的,因为它只释放第一个节点,并使其他节点无法访问,从而导致内存泄漏。要解决这个问题,您需要一个一个地释放节点,如下所示:
struct node *tmp = root;
while(root) {
tmp = root->next;
free(root);
root = tmp;
}发布于 2011-03-26 13:01:50
问题在add()中
if(root==NULL)这个测试是错误的:通过引用传递的根从来都不是空的(参见主,它包含根节点的地址)。您应该正确测试rrot节点是否为NULL:
if (*root == NULL)我还要补充一点,您释放分配给ist的内存的方式是错误的:
free(root)只会释放根节点,但会泄漏子节点.
https://stackoverflow.com/questions/5442423
复制相似问题