谁能解释一下递归结束后这些语句是如何执行的
Can anyone explain how the statements are being executed once recursion is over?
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;
}
所做的没有任何用处,看起来像是试图反转列表本身,但这应该以不同的方式完成,没有分配。
相关文章:
- 如何及时执行if语句?
- 获取上次执行的返回语句的行
- 如何仅在父循环的所有迭代都为真时才执行嵌套的 if 语句?
- C 程序如果功能中的语句不执行.在逻辑上似乎是错误的
- 否则,如果语句意外执行,则表现为其他语句
- 是否可以在一个语句中执行2个相反的位置操作
- 在我的switch语句完全执行之前,我的while循环进入第二次迭代,我用c ++编码
- switch 语句未执行
- 如何实现 throw 语句来执行整数值
- if 语句始终执行
- 案例语句不执行
- C++if-else语句继续执行if,而不是else下的代码
- If语句和else If语句将执行
- if语句未执行
- 为什么无论输入如何,我的第一个 "if" 语句都会执行?
- 嵌套的if-else语句只执行一个条件(c++)
- 为什么c++中返回语句后执行停止
- 我的简单'if'语句没有执行代码中的内容
- while 循环之后的语句未执行
- 在多个if语句中执行相同的操作,如何减少代码冗余