【问题标题】:Reversing a linked list (by recursion) not working反转链表(通过递归)不起作用
【发布时间】:2014-07-30 19:04:03
【问题描述】:

我试图编写代码来反转链表,但输出错误。 有什么我想念的吗?

这里是函数

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;

}

后显示功能

Input 409765
Output 4

【问题讨论】:

  • 你为什么将headreverse 传递为**
  • 那么,问题是什么?
  • 因为你反向后丢失了头节点。

标签: c++ c pointers linked-list heap-memory


【解决方案1】:

*headreverse = p 毫无意义。每次都应该设置*headreverse = p->next向前移动,直到到达最后一个节点。

无论如何,我更改了您的代码以使其正常工作:

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;
}

【讨论】:

    【解决方案2】:

    对于单个列表,使用两个两个指针,以更新列表,因为您不能返回。

    这是我的代码。希望它能帮助你理解概念。

    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;             
    }
    

    如果我可以更准确,请提供建议。

    【讨论】:

      【解决方案3】:

      您的 headreverse 未分配给列表的新头部。请务必为您的函数使用 2 个参数,1)初始列表的头部 2)当前节点(与您的 headreverse 相同)

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

      【讨论】:

      • 这里headheadreverse有什么区别?请解释一下。
      • head 是初始链表的头部。您在其中使用的 headreverse 实际上只是您在列表中引用的一个节点。假设你的链表是 1->2->3->4 现在你的程序是 1结论:您在程序中更改的只是每个节点的下一个指针。 所以要么按照我的建议做,要么将reverselinklist(&(p->next)); 更改为*headreverse = p->next; reverselinklist(headreverse);
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      相关资源
      最近更新 更多