【问题标题】:Help with recursive function递归函数帮助
【发布时间】:2011-06-21 03:24:39
【问题描述】:

我有以下代码来合并两个排序的链表:

struct node* merge(struct node* a, struct node* b)
{
        struct node dummy;     

        struct node* tail = &dummy; 

        dummy.next = NULL;
        while(1)
        {
                if(a == NULL)
                {
                        tail->next = b;
                        break;
                }
                else if (b == NULL)
                {
                        tail->next = a;
                        break;
                }
                if (a->data <= b->data)
                {
                        MoveNode(&(tail->next), &a);
                }
                else
                {
                        MoveNode(&(tail->next), &b);
                }
                tail = tail->next;
        }
        return(dummy.next);
} 

void MoveNode(struct node** destRef, struct node** sourceRef)
{
        struct node* newNode = *sourceRef;

        *sourceRef = newNode->next;

        newNode->next = *destRef;

        *destRef = newNode;
}

而且效果很好。我试图把它变成一个递归方法,这就是我得到的:

struct node* Merge(struct node* a, struct  node* b)
{
        struct node* result;

        if (a == NULL)
                return(b);
        else if (b==NULL)
                return(a);

        if (a->data <= b->data)
        {                
                result = Merge(a->next, b);
        }
        else
        {                
                result = Merge(a, b->next);
        }
        return(result);
}

但结果中缺少许多节点。怎么了?

【问题讨论】:

  • 我认为您忘记在递归函数中实际构建输出列表。在您的归纳案例中,为什么不向从递归调用获得的列表中添加一些内容?

标签: c data-structures recursion linked-list


【解决方案1】:

您的基本条件是正确的。但是你的递归条件有问题。

当您将a 的数据与b 的数据进行比较时,您并未将节点a 或节点b 复制到result

试试:

struct node* result; 

if (a == NULL)         
        return(b);                     
else if (b==NULL)                              
        return(a);                                             

if (a->data <= b->data)                                                
{          
        // make result point to node a.                                        
        result = a;      
        // recursively merge the remaining nodes in list a & entire list b
        // and append the resultant list to result.
        result->next = Merge(a->next, b);
}
else                                    
{                
        result = b;
        result->next = Merge(a, b->next);               
}
return(result);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-07
    • 2013-10-31
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 2011-02-02
    相关资源
    最近更新 更多