谁能解释一下递归结束后这些语句是如何执行的

Can anyone explain how the statements are being executed once recursion is over?

本文关键字:语句 何执行 执行 能解释 一下 递归 结束      更新时间:2023-10-16
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。

基本上,你用"head = 2"->"next = 1"->"next = 4"-

>"next = 5"->"next = NULL"来调用ReversePrint()。然后才来了第一cout,打印你好。然后程序回溯调用堆栈(回到节点"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;
}
不需要

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

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