任何人都可以解释一旦递归结束后语句是如何执行的?

时间:2016-05-29 21:20:22

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

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

输出是: - 你好 五 你好 4 你好 1 你好 2 喂

我不明白如何在链接列表的最后一个元素(在这种情况下的第一个元素,即反向顺序)之前打印hello。

2 个答案:

答案 0 :(得分: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;
}

做了什么没有任何目的,它看起来像是试图扭转列表本身,但是应该以不同的方式完成,而不进行分配。

答案 1 :(得分:2)

基本上,您使用“head = 2”调用ReversePrint() - &gt; “next = 1” - &gt; “next = 4” - &gt; “next = 5” - &gt; “next = NULL”。只有到了第一个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;
}