链表的反转(逆序)- 递归方法实现:
- 初始化了一条单链表,内部数据依次为 0 1 2 3 4 5 6
- 递归调用判断下个结点是否为空
- 尾结点返回其地址,作为新的头结点
- 从后向前改变指针域指向
- 最后返回新头结点
程序执行结果:
实现代码:
#include <stdlib.h>
#include <stdio.h>
typedef struct linklist
{
int data;
struct linklist *next;
}Node;
/* 递归逆序 */
Node* linklist_reverse(Node *head)
{
/* 空表 或者 头下一结点空时返回头结点地址*/
if(head == NULL || head->next == NULL)
{
return head;
}
/* 接收上次返回的头结点 */
Node *newhead = linklist_reverse(head->next);
head->next->next = head;
head->next = NULL;
/* 返回 第一次返回的头结点 作为新的头结点*/
return newhead;
}
/* 初始化一条链表 */
Node *linklist_create()
{
Node *head = (Node *)malloc(sizeof(Node));
if(head == NULL)
{
perror("malloc");
return NULL;
}
head->next = NULL;
int n = 7;
while(n--)
{
Node *new = (Node *)malloc(sizeof(Node));
if(new == NULL)
{
perror("malloc");
return NULL;
}
new->data = n;
new->next = head->next;
head->next = new;
}
//删除头结点
Node *p = head;
head = head->next;
free(p);
return head;
}
/* 打印链表 */
void linklist_print(Node *head)
{
Node *p = head;
printf("List:");
while(p != NULL)
{
printf("%d ",p->data);
p = p->next;
}
puts("");
}
int main()
{
//初始化一跳链表
Node *head = linklist_create();
//逆序前
linklist_print(head);
//递归逆序
Node *newhead = linklist_reverse(head);
//逆序后
linklist_print(newhead);
return 0;
}