【问题标题】:insert single linked list at the end recursively in c在c中递归地在末尾插入单个链表
【发布时间】:2017-06-13 21:09:24
【问题描述】:

谁能告诉我我的代码有什么问题?
我想创建非返回函数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;
    }
  }
}

【问题讨论】:

  • 这个条件 temp->data data 是什么意思?它与“列表末尾”有什么关系?
  • 你遇到了什么错误?
  • 您正在询问添加到列表中,但代码是关于添加到树中。没有struct node 的定义。即使添加它,代码也无法正确编译。请修复编译错误,它们在这里有意义。
  • 您不应该递归地执行此操作。如果您的列表很大,您肯定会破坏堆栈。

标签: c tree insert binary-tree


【解决方案1】:

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

您的意思似乎是以下。

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

【讨论】:

  • 非常干净简洁的树插入代码,加我的1
  • 这不是问题吗?您的函数将修改传递给它的原始根指针。
  • @Coldspeed 是的,它会在树为空且指针等于NULL的情况下修改根。但这不是问题。这是一个解决方案。
  • @VladfromMoscow 并且当它不为 NULL 时,您仍然会看到它在递归情况下被更新。因此,在非空树中,这将始终使根指向叶子,还是我弄错了?
  • @Coldspeed 在树不为空的情况下,更新的是 ( *phead )->pLeft 和 ( *phead )->pRight 。因为 phead 设置了这些节点的地址。
猜你喜欢
  • 2016-10-11
  • 2015-07-07
  • 1970-01-01
  • 2011-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
  • 2015-02-08
相关资源
最近更新 更多