我正在使用以下代碼在此處找到以開始涉及樹數據結構的項目。無法理解此函數返回
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爲無效的功能,但無論是在錯誤的這些修改的結果(更不用提在我的代碼執行發現確實工作)。我錯過了什麼?
你可以調用一個返回值並且不使用t的方法他回報了價值。這是你的主要做的。 – litelite
你認爲作者是這樣寫的嗎? – user178831
因爲他根本不需要使用返回值,但在其他情況下可能有用 – litelite