逆置后为什么与预期输出的结果不同,应该怎么改?顺便能解释一下逆置函数的原理吗,不是太懂

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
int data;
struct node next;
}Node;
Node
CreatList(int n)
{
Node *head,p,end;
head=(Node
)malloc(sizeof(Node));
end=head;
for(int i=0;i<n;i++)
{
p=(Node*)malloc(sizeof(Node));
scanf("%d",&p->data );
end->next=p;
end=p;
}
end->next=NULL;
return head;
}
Node
ReverseList(Node *head)
{
Node *newHead;
if(head==NULL||head->next==NULL)
return head;
newHead=ReverseList(head->next);
head->next->next=head;
head->next=NULL;
return newHead;
}
void ShowList(Node *phead)
{
for(phead=phead->next;phead!=NULL;phead=phead->next)
printf("%d ",phead->data);
printf("\n");
}
int main(void)
{
Node *phead;
int n;
scanf("%d",&n);
phead = CreatList(n);
printf("链表逆置前的数据:\n");
ShowList(phead);
phead = ReverseList(phead);
printf("链表逆置后的数据:\n");
ShowList(phead);
return 0;
}

img

兄弟你的基础有点差啊,函数放回那,你定义返回的是一个变量,实际返回值是变量指针,还有链表结构定义都有问题

上面大哥给你说了问题,简单解释下你写的反转链表的函数意思:
理解递归的时候,不要把递归带入你的小脑袋,你的小脑袋才能压几个栈?你应该清楚的是,什么时候结束递归,什么时候进入递归,每次递归要做什么。如这个反转链表:

Node ReverseList(Node *head)
{
    Node *newHead;
    // 结束递归:显而易见,当传入的参数为null,或者next为null则跳出递归,因为需要两个节点(当前和下一个)反转
    if(head==NULL||head->next==NULL)
        return head;
    // 进入递归:因为要反转,就直接先进入到链表尾部,从尾部开始反转
    newHead=ReverseList(head->next);
    // 做什么:反转,反转就是假设链表为 1 -> 2 -> null,变成 2 -> 1 -> null
    // head = 1, head.next = 2, head.next.next = null 写成代码就是下面那样
    head->next->next=head; // 经过这一步后,会形成一个环形链表, 1 -> 2 -> 1 -> 2...
    head->next=NULL; // 然后只要把环形链表断开就行了, 让 1 -> null,最后就是 2 -> 1 -> null 
    // 反转完毕返回
    return newHead;
}