C++ 有人能解释递归结束后语句是如何执行的吗? void ReversePrint(节点*头部) { Node*sec=(Node*)malloc(sizeof(Node)); sec->next=NULL; 秒->数据=0; if(head!=NULL) { 反向打印(头->下一步); 节点*tmp=sec; tmp->数据=头部->数据; cout
tmp和sec是不必要的,每次都会导致内存泄漏。 请将其移除并改用:C++ 有人能解释递归结束后语句是如何执行的吗? void ReversePrint(节点*头部) { Node*sec=(Node*)malloc(sizeof(Node)); sec->next=NULL; 秒->数据=0; if(head!=NULL) { 反向打印(头->下一步); 节点*tmp=sec; tmp->数据=头部->数据; cout,c++,recursion,linked-list,singly-linked-list,C++,Recursion,Linked List,Singly Linked List,tmp和sec是不必要的,每次都会导致内存泄漏。 请将其移除并改用: 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
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;
}
cout data基本上,您使用“head=2”->“next=1”->“next=4”->“next=5”->“next=NULL”调用ReversePrint()
,然后第一个cout
,打印hello。然后程序回溯调用堆栈(返回节点“5”),打印5,然后再打印hello。然后再次回溯(返回节点“4”)……等等
如果您想避免第一个“你好”(并考虑其他答案),请尝试以下方法:
void ReversePrint(Node *node)
{
//cout << "(";
if (node != NULL)
{
ReversePrint(head->next);
cout << node->data << endl;
}
cout << "hello" << endl;
//cout << "hello" << ")" << endl;
}
void ReversePrint(节点*Node)
{
if(node==NULL)//确保列表的第一个元素不是NULL
返回;
如果(节点->下一步!=NULL)
反向打印(节点->下一步);
提到编程语言可能会有所帮助。@Juhana我现在已经提到了编程语言,谢谢你的建议。我建议使用调试器跟随这段代码,以了解执行流程。另外请注意,这段代码正在泄漏内存。此函数的输出与文中给出的相同((((((((((((hello)5)hello)4)hello)1)hello)2)hello
-这是节点为null时打印的第一个hello(并且跳过if语句)。
void ReversePrint(Node *node)
{
//cout << "(";
if (node != NULL)
{
ReversePrint(head->next);
cout << node->data << endl;
}
cout << "hello" << endl;
//cout << "hello" << ")" << endl;
}
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;
}