谁能告诉我我的代码有什么问题吗?
我想创建非返回函数void在链接列表的末尾插入一个节点。

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;
    }
  }
}

最佳答案

您的代码太复杂,结果有错误。例如,存在内存泄漏。

看来您的意思如下。

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 );
    }
}

07-23 14:18