简体   繁体   English

使用 void function 反转链接列表

[英]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 -我看到了一种使用 function 的递归来反转链接列表的方法,但是 function 返回节点数据类型,但我想使用 ZC1C425268E68385D1AB5074C17A94F1

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.对于链表 1->2->3->4->NULL,它给出的 output 为 4->1->NULL。 I don't understand where my code goes wrong.我不明白我的代码哪里出错了。 An explaination of the wrong output will be appreciated.将不胜感激对错误 output 的解释。

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.请注意,“temp”始终指向最后一个节点(您称为 4),因为您在 while 循环中迭代到 next==NULL。 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).它返回到上一个调用,将“next”节点的“next”指针设置为当前节点(因此“4”指向“3”),然后将当前节点的“next”指针设置为 NULL(这很重要,因为它命中'1'它必须指向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; 
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM