递归地在末尾插入单链表c

问题描述:

任何人都可以告诉我我的代码有什么问题吗?
我想创建非返回函数void在链表的末尾插入一个节点。递归地在末尾插入单链表c

void insert_tail_Recursively(struct node **phead, int key) { 
    if (*phead == NULL) { 
    Node*temp = malloc(sizeof(Node)); 
    temp->data = key; 
    temp->pLeft = temp->pRight = NULL; 
    *phead = temp; 
    } else { 
    Node*temp = malloc(sizeof(Node)); 
    temp->data = key; 
    temp->pLeft = temp->pRight = NULL; 

    /* data more than root node data insert at right */ 
    if ((temp->data > (*phead)->data) && ((*phead)->pRight != NULL)) 
     insert_tail_Recursively((*phead)->pRight, key); 
    else if ((temp->data > (*phead)->data) && ((*phead)->pRight == NULL)) { 
     (*phead)->pRight = temp; 

    } 

    /* data less than root node data insert at left */ 
    else if ((temp->data < (*phead)->data) && ((*phead)->pLeft != NULL)) 
     insert_tail_Recursively((*phead)->pLeft, key); 
    else if ((temp->data < (*phead)->data) && ((*phead)->pLeft == NULL)) { 
     (*phead)->pLeft = temp; 
    } 
    } 
} 
+0

这是什么条件温度 - >数据数据是什么意思?它与“名单的结尾”有什么关系? –

+0

你有什么错误? –

+1

您正在询问是否添加到列表中,但代码是关于添加到树中的。没有'struct node'的定义。即使在添加之后,代码也无法正确编译。请修正编译错误,这里有意义。 – ArturFH

您的代码过于复杂,导致错误。例如有内存泄漏。

看来你的意思是以下。

void insert_tail_Recursively(struct node **phead, int key) 
{ 
    if (*phead == NULL) 
    { 
     *phead = malloc(sizeof(struct node)); 
     (*phead)->data = key; 
     (*phead)->pLeft = (*phead)->pRight = NULL; 
    } 
    else 
    { 
     phead = key < (*phead)->data ? &(*phead)->pLeft : &(*phead)->pRight; 
     insert_tail_Recursively(phead, key); 
    } 
} 
+0

非常干净和简洁的树插入代码,加我1从 – BlueStrat

+0

这不是一个问题吗?您的函数将修改传递给它的原始根指针。 –

+0

@Coldspeed是的,当树为空且指针等于NULL时,它将修改根目录。但这不是问题。这是一个解决方案。 –