无法理解此函数返回

问题描述:

我正在使用以下代码在此处找到以开始涉及树数据结构的项目。无法理解此函数返回

struct node{ 

    int ID; 
    struct node* next; 
    struct node* child; 
}; 

typedef struct node node; 

node* new_node(int); 
node* add_sibling(node*, int); 
node* add_child(node*, int); 


int main() 
{ 
    int i; 
    node *root = new_node(0); 
    for (i = 1; i <= 3; i++) 
     add_child(root, i); 
} 

node * new_node(int ID) 
{ 
    node* new_node =(node*) malloc(sizeof(node)); 
    if (new_node) { 
     new_node->next = NULL; 
     new_node->child = NULL; 
     new_node->ID = ID; 
    } 

    return new_node; 
} 

node* add_sibling(node* n, int ID) 
{ 
    if (n == NULL) 
     return NULL; 

    while (n->next) 
     n = n->next; 

    return (n->next = new_node(ID)); 
} 

node* add_child(node* n, int ID) 
{ 
    if (n == NULL) 
     return NULL; 
    if (n->child) 
     return add_sibling(n->child, ID); 
    else 
     return (n->child = new_node(ID)); 
} 

我是初学C/C++和一般编程。我想我明白除了add_child函数以外的所有代码。该函数似乎返回一个指向节点的指针,但是当它在main中调用时,它似乎被称为无效函数。我还以为要调用的函数这样

*root = add_child(root,i); 

像new_node是如何调用,或写add_child为无效的功能,但无论是在错误的这些修改的结果(更不用提在我的代码执行发现确实工作)。我错过了什么?

+1

你可以调用一个返回值并且不使用t的方法他回报了价值。这是你的主要做的。 – litelite

+0

你认为作者是这样写的吗? – user178831

+1

因为他根本不需要使用返回值,但在其他情况下可能有用 – litelite

重写该函数将如下所示。

node* add_child(node* n, int ID) 
{ 
    // For null pointer return null 
    if (n == NULL) 
    { 
     return NULL; 
    } 

    // If element has child add a sibling to that child 
    if (n->child) 
    { 
     node* sibling_for_child = add_sibling(n->child, ID); 
     return sibling_for_child; 
    } 
    else 
    { 
     // Otherwise just add element as a child 
     node* child_node = new_node(ID); 
     n->child = child_node; 
     return child_node; 
    } 
} 

分配的结果是分配的值(*)就像这个链接分配:

int a, b; 
a = b = 3; 

这实际上是:

a = (b = 3); 

b = 3; 
a = b; 
+0

谢谢,您重写代码的方式更加清晰,我将使用它。然而,我的困惑源于未被使用的功能的恢复,但上面的评论者清楚地意识到了这一点。 – user178831

+0

这是如何解决OP的问题的:“但是当它在main中调用时,它似乎被称为好像它是一个无效函数”? – babon

+0

它没有。这个答案更多的是关于“我认为我理解除了add_child函数之外的所有代码” – teivaz