使用双指针和递归反转链表

时间:2019-12-18 14:50:52

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

我知道有很多答案,但是我只是无法理解为什么我的代码不起作用。 你能帮忙吗?

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;作为全局变量,在我看来,我必须使用双指针。

1 个答案:

答案 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 );
相关问题