Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

c++ - Reversing a Linked List with a void function

I saw a approach to reverse a Linked list using recursion with a function but that function returns a node data type but I wanted to use a function with void return type and I made an approach -

void reverseLLrecursion(node* &head){
    if(head==NULL||head->next==NULL){        
        return ;
    }
    else{
        
        node* temp=head ;
        while(temp->next!=NULL){
             temp=temp->next ;
        }
        
        reverseLLrecursion(head->next) ;
        head->next->next=head ;
        head->next=NULL ;
        head=temp ;
    }

}

for a linked list 1->2->3->4->NULL it gives a output of 4->1->NULL. I don't understand where my code goes wrong. An explaination of the wrong output will be appreciated.

question from:https://stackoverflow.com/questions/65908257/reversing-a-linked-list-with-a-void-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Basically you don't need this line:

        head=temp;

Notice, that "temp" always points to last node (called 4 by you), because you iterate up to next==NULL in while loop. There is no point in holding "temp" value.

When your recursion hits first condition:

head->next==NULL

it returns to the previous call, sets "next" pointer of the "next" node to current node (so '4' is pointing to '3'), and then sets current's node "next" pointer to NULL (this is important, because it hits '1' it has to point to NULL).

You can delete some of your code, this should do the trick:

    void reverseLLrecursion(node* &head){
        if(head->next==NULL){        
            return ;
        }
        else
        {
            reverseLLrecursion(head->next);
            head->next->next=head;
            head->next=NULL; 
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...