messiuuuu 2023-12-25 14:40 采纳率: 95.2%
浏览 2
已结题

递归方式反转链表问题

这是一个使用递归方式反转链表,但是我最后调试后发现反转后的头指针位置没变化,请各位看看我哪里出问题了

#include<stdio.h>
#include<stdlib.h>
typedef struct node{
    int data;
    struct node *next;
}Node;

void Insert(Node **head,int x)
{
    Node *temp=(Node*)malloc(sizeof(Node));
    temp->data=x;
    temp->next=NULL;
    if(*head==NULL)
    {
        *head=temp;
        return;
    }else
    {
        Node *temp1=*head;
        while(temp1->next!=NULL)
        {
            temp1=temp1->next;
        }
        temp1->next=temp;
    }
}
void Print(Node *head)
{
    while(head!=NULL)
    {
        printf("%d ",head->data);
        head=head->next;
    }
    printf("\n");
}
Node *Reverse(Node *temp)
{
    if(temp->next==NULL)
    {
        return temp;
    }else
    {
        Reverse(temp->next);
        Node *q=temp->next;
        q->next=temp;
        temp->next=NULL;
    }
}

int main()
{
    Node *head=NULL;
    
    Insert(&head,1);
    Insert(&head,2);
    Insert(&head,3);
    Insert(&head,4);
    Insert(&head,5);
    Print(head);
    head=Reverse(head);
    Print(head);
    
    return 0;
}

  • 写回答

2条回答 默认 最新

  • 编程乐学 2023-12-25 18:57
    关注

    在递归反转链表的代码中,问题出在递归函数的返回值上。在递归函数中,应该返回反转后的头节点,但是您的代码中没有正确返回头节点。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 1月2日
  • 已采纳回答 12月25日
  • 创建了问题 12月25日

悬赏问题

  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析