【问题标题】:Can anyone explain how the statements are being executed once recursion is over?谁能解释一下递归结束后语句是如何执行的?
【发布时间】:2016-05-29 21:20:21
【问题描述】:
void ReversePrint(Node *head)
{
    Node *sec=(Node *)malloc(sizeof(Node));
    sec->next=NULL;
    sec->data=0;
    if(head!=NULL)
    {
        ReversePrint(head->next);
        Node *tmp=sec;
        tmp->data=head->data;
        cout<<tmp->data<<endl;
        tmp=tmp->next;
    }
cout<<"hello"<<endl;
}

输入:2 1 4 5

输出是:- 你好 5 你好 4 你好 1 你好 2 你好

我不明白如何在链表的最后一个元素(本例中为第一个元素,即倒序)之前打印 hello。

【问题讨论】:

  • 提及编程语言会有所帮助。
  • @Juhana 我已经提到了编程语言,感谢您的建议
  • 我建议使用调试器跟踪此代码以了解执行流程。另请注意,此代码正在泄漏内存。

标签: c++ recursion linked-list singly-linked-list


【解决方案1】:

基本上,您使用“head = 2”->“next = 1”->“next = 4”->“next = 5”->“next = NULL”调用ReversePrint()。然后才出现第一个cout,打印hello。然后程序回溯调用堆栈(返回节点“5”),打印 5 后跟 hello。然后再次回溯(回到节点“4”)......等等。

如果你想避免第一个“你好”(并考虑到其他答案),试试这个:

void ReversePrint( Node * node )
{
    if( node == NULL )  // to make sure the very first element of the list is not NULL
        return;

    if( node->next != NULL )
        ReversePrint( node->next );

    cout << node->data << endl;
    cout << "hello" << endl;
}

【讨论】:

    【解决方案2】:

    tmp 和 sec 是不需要的,每次都会导致内存泄漏。 删除它们并改用:

    cout << head->data << endl;
    

    所以:

    void ReversePrint(Node *node)
    {
        //cout << "(";
        if (node != NULL)
        {
            ReversePrint(head->next);
            cout << node->data << endl;
        }
        cout << "hello" << endl;
        //cout << "hello" << ")" << endl;
    }
    

    所做的事情没有任何目的,它看起来像是试图反转列表本身,但应该以不同的方式完成,没有分配。

    【讨论】:

    • 此函数的输出与问题中给出的相同
    • ((((((((hello) 5) hello) 4) hello) 1) hello) 2) hello - 当 node 为空时打印第一个 hello(并且跳过 if 语句)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    相关资源
    最近更新 更多