当前位置:网站首页>反转链表-递归反转法
反转链表-递归反转法
2022-07-30 11:23:00 【代码骑士】
(1)思想:和迭代反转法的思想恰好相反,递归反转法的实现思想是从链表的尾节点开始,依次向前遍历,遍历过程依次改变各节点的指向,即另其指向前一个节点。
(2)实现(建议先看代码,再看图解,使理解更加深刻):
开始递归:
new_head经过三次函数递归的调用来到了链表的最后一个结点,因为new_head=head->next,所以head始终保持在new_head的前一个结点处。

递归到最后一层时:

开始逐层出递归:



递归结束。
最后的结果为:
代码片段:
link* recursive_reverse(link* head) {
//出递归条件
if (head == NULL || head->next == NULL)
{
return head;
}
else
{
//new_head一直找到链表中的最后一个元素的地址
link *new_head = recursive_reverse(head->next);
//出递归后,将链表
head->next->next = head;
head->next = NULL;
return new_head;
}
}完整代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct Link{
int elem;
struct Link* next;
}link;
link* initLink(){
int i;
//定义头指针
link* head=NULL;
//定义首元结点
link* temp=(link*)malloc(sizeof(link));
//首元结点初始化
temp->elem=1;
temp->next=NULL;
head=temp;
//创建其他结点
for(i=2;i<5;i++){
link* a=(link*)malloc(sizeof(link));
a->elem=i;
a->next=NULL;
temp->next=a;
temp=temp->next;
}
//返回头指针的地址
return head;
}
void printLink(link* head){
link* p=head;
while(p){
printf("%d ",p->elem);
p=p->next;
}
printf("\n");
}
link* recursive_reverse(link* head) {
//出递归条件
if (head == NULL || head->next == NULL)
{
return head;
}
else
{
//new_head一直找到链表中的最后一个元素的地址
link *new_head = recursive_reverse(head->next);
//出递归后,将链表
head->next->next = head;
head->next = NULL;
return new_head;
}
}
int main()
{
link*p=initLink();
printf("原始链表:");
printLink(p);
printf("反转链表:");
p=recursive_reverse(p);
printLink(p);
return 0;
}
输出结果:

边栏推荐
- Typroa 替代工具marktext
- STM32F1 reads MLX90632 non-contact infrared temperature sensor
- Typroa alternative tool marktext
- 基于.NetCore开发博客项目 StarBlog - (16) 一些新功能 (监控/统计/配置/初始化)
- Native js create table
- The package of idea is not hollow
- Swift common extension classes and simple encapsulation
- 模糊离散事件系统的可测性
- Beyond Stream Processing!The 4th real-time computing Flink challenge is launched, and 490,000 prizes are waiting for you!
- 简述controller,service,repository注解的用法(谈谈application.properties的作用)
猜你喜欢

C语言 — 位运算操作

Microsoft SQL服务器被黑客入侵 带宽被窃取

2022-07-29 Gu Yujia Study Notes Exception Handling

电流继电器JL-8GB/11/AC220V

Beyond Stream Processing!The 4th real-time computing Flink challenge is launched, and 490,000 prizes are waiting for you!

域名怎么注册备案解析?

时间序列曲线相似性

面试官:Redis中的布隆过滤器与布谷鸟过滤器,你了解多少?

I built another wheel: GrpcGateway

VSCode更改插件的安装位置
随机推荐
简述controller,service,repository注解的用法(谈谈application.properties的作用)
流水线上的农民:我在工厂种蔬菜
单片机工程师笔试题目归纳汇总
Introduction to IoT Technologies: Chapter 6
Detailed explanation of @RequestBody and @ResponseBody
柔性机械系统分布参数建模及其控制的研究与进展
contentDocument contentWindow,canvas 、svg,iframe
TensorFlow自定义训练函数
【数据库基础】redis使用总结
【JZ64 求1+2+3+...+n】
C语言 — 位运算操作
Interviewer: Redis bloom filter and the cuckoo in the filter, how much do you know?
重写并自定义依赖的原生的Bean方法
时间序列曲线相似性
2022-07-29 Gu Yujia Study Notes Exception Handling
Differences between lock spin and mutex usage scenarios
The package of idea is not hollow
淘宝/天猫淘宝评论问答列表接口 API
decodeURIComponent(), eval(), encodeURIComponent()
汇编实现冒泡排序