我知道有很多答案,但是我只是无法理解为什么我的代码不起作用。 你能帮忙吗?
void reverse_LList_R_fail(Node** head) {
Node* current = *head;
if(current->next == nullptr) {
*head = current;
return;
}
reverse_LList_R_fail(&(current)->next);
current->next->next = current;
current->next = nullptr;
}
PS:在我的LList实现中,我定义了Node * head = nullptr;作为全局变量,在我看来,我必须使用双指针。
答案 0 :(得分:1)
对于初学者来说,该功能不会检查*head
是否等于nullptr
。因此该函数具有未定义的行为。
通过指针传递给函数的原始头也不会更改。
该函数的外观如下
void reverse_LList_R_fail( Node **head )
{
if ( *head && ( *head )->next )
{
Node *current = *head;
*head = ( *head )->next;
reverse_LList_R_fail( head );
current->next->next = current;
current->next = nullptr;
}
}
该函数的调用方式类似于
reverse_LList_R_fail( &head );