【问题标题】:Problems using recursion to reverse a linked list使用递归反转链表的问题
【发布时间】:2013-10-22 14:16:33
【问题描述】:

我被要求编写一个驱动函数来调用递归函数。我想知道我需要在驱动程序函数中做什么。

这个程序是反转一个链表。

void invert_r()
{
    //This is the driver function for recursive_invert

    nodeType<Type> *p, *q;

    q = first;
    p = first;
    recursive_invert(q, p);
}
nodeType<Type>* recursive_invert(nodeType<Type> *q, nodeType<Type> *p)
{
    //Invert a linked list using recursion.
    //DO NOT create any new node in your implementation
    if(p -> link == NULL)
    {   
        q -> link = p;
        return p;
    }
    else
    {
        recursive_invert(p -> link, q) -> link = p;
    }
    return p;
}

【问题讨论】:

  • 很难说只要我们看不到first 是什么。否则一切看起来都很好。这段代码有什么具体问题?
  • @g-makulik "first" 是链表的第一个元素。我对驱动函数的使用以及如何使用它然后调用我的递归函数感到困惑......
  • 该函数的输出是首先通过迭代的方法反转链表。然后通过实现 invert_r() 调用递归的来转换回链表
  • 如果 first 是链表的第一个元素,我认为它们必须是 nodeType 的成员,所以在 invert_r 函数应该是这样的:q = q->first;
  • 由于您需要传递(指向)一个节点和(指向)下一个节点的(指针),您需要nodeType&lt;Type&gt; *p = first; nodeType&lt;Type&gt; *q = p-&gt;link; 和可能first = recursive_invert(p, q);,不是吗?至少,您不应该随意丢弃递归函数的返回值,因为它现在是列表的头部(如果丢失它,您将无法再次到达列表的开头)。

标签: c++ function recursion linked-list


【解决方案1】:
void recursiveReverse(struct node** head_ref)
{
    struct node* first;
    struct node* rest;

    /* empty list */
    if (*head_ref == NULL)
       return;   

    /* suppose first = {1, 2, 3}, rest = {2, 3} */
    first = *head_ref;  
    rest  = first->next;

    /* List has only one node */
    if (rest == NULL)
       return;   

    /* reverse the rest list and put the first element at the end */
    recursiveReverse(&rest);
    first->next->next  = first;  

    /* tricky step -- see the diagram */
    first->next  = NULL;          

    /* fix the head pointer */
    *head_ref = rest;              
}

【讨论】:

  • 您的代码看起来不像 OP 的代码。它有不同的签名和不同的结构成员。
  • John 这只是为了说明,就像一个算法。
  • 请注意,我们希望得到解决问题中具体问题的答案。如果您有一个非常相关的替代方案,您可以考虑添加它 - 但请务必首先解决问题并准确解释原因。
  • 一些解释会很好,但如果你补充一下,我认为这可能是一个很好的答案;-)
猜你喜欢
  • 2019-01-09
  • 2020-07-22
  • 2018-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-04
  • 1970-01-01
相关资源
最近更新 更多