图解:
注意:1. head->next->next 是下一个节点指向自己
2. head.next = NULL这步操作其实只有递归到原链表头的时候才有用
#include <stdio.h>
#include<stdlib.h>
typedef struct _Node
{
struct _Node* next;
int a;
}Node;
Node* reverseList(Node* head)
{
if(head->next == NULL) return head;
if(head==NULL) return NULL;
Node* p = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return p;
}
Node* initList(Node* head)
{
head = (Node*)malloc(sizeof (Node));
head->a = 0;
head->next = NULL;
return head;
}
void insertList(Node* head,int a)
{
while (head->next!=NULL)
{
head = head->next;
}
Node* cur = (Node*)malloc(sizeof (Node));
cur->a = a;
cur->next = NULL;
head->next =cur;
}
void traverseList(Node* head)
{
while (head->next!=NULL)
{
printf("%d\n",head->a);
head = head->next;
}
printf("%d\n",head->a);
}
int main()
{
Node* head = NULL;
head = initList(head);
insertList(head,1);
insertList(head,2);
insertList(head,3);
insertList(head,4);
insertList(head,5);
Node* p=reverseList(head);
traverseList(p);
printf("Hello World!\n");
return 0;
}