简体   繁体   English

反向链接列表(通过递归)不起作用

[英]Reversing a linked list (by recursion) not working

I was trying to write a code to reverse the linked list but getting wrong output. 我试图编写代码以反向链接列表,但输出错误。 Is there something I am missing. 有什么我想念的吗?

Here is the function 这是功能

void reverselinklist( struct node **headreverse)
{
    struct node *p = *headreverse;
    if(p->next == NULL)
    {
        *headreverse = p;
        return;
    }

    reverselinklist(&(p->next));
    p->next->next = p;
    p->next = NULL;

}

After display function 后显示功能

Input 409765
Output 4

*headreverse = p is meaningless. *headreverse = p毫无意义。 You should set *headreverse = p->next each time to move forward, until the last node is reached. 您应该每次都设置*headreverse = p->next向前移动,直到到达最后一个节点。

Anyway, I changed your code to make it work: 无论如何,我更改了您的代码以使其起作用:

void reverselinklist(struct node **headreverse)
{
    struct node *p = *headreverse;
    if(p->next == NULL){
        return;
    }
    *headreverse = p->next;
    reverselinklist(headreverse);
    p->next->next = p;
    p->next = NULL;
}

For single list use two two pointers, to update list as you can not go back. 对于单个列表,请使用两个两个指针,以更新列表,因为您无法返回。

Here is my code. 这是我的代码。 Hope it will help you to understand concept. 希望它能帮助您理解概念。

void reverselinklist(struct node** head_ref)
{
    struct node* first;
    struct node* rest;

    first = *head_ref; 
    rest  = first->next;

    if (rest == NULL)
       return;  

    reverselinklist(&rest);
    first->next->next  = first; 

    first->next  = NULL;         

    *head_ref = rest;             
}

If it could me more precise please provide suggestions. 如果可以,请提供建议。

Your headreverse is not being assigned to the new head of the list. 您的headreverse没有分配给列表的新标题。 Be sure to use 2 arguments for your function, 1) head of the initial list 2) current node(same as your headreverse) 确保为函数使用2个参数,1)初始列表的头部2)当前节点(与headreverse相同)

if(p->next == NULL)
{
    *head = p; //instead of headreverse use head
    return;
}

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

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