当前位置:网站首页>剑指 Offer 24. 反转链表
剑指 Offer 24. 反转链表
2022-07-26 11:46:00 【[email protected]】

解法一:迭代
使用三个变量,pre保存上一次遍历结束的节点,cur保存当前遍历到的节点,next保存下一个节点
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre=null,cur=head,next;
while(cur!=null){
next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
return pre;
}
}
//O(n)
//O(1)
解法二:递归
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null){
//链表为空或者只有1个节点
return head;
}
ListNode newHead=reverseList(head.next);//反转后面n-1个节点
head.next.next=head;//原来的第2个节点指向旧的头节点
head.next=null;//旧的头节点指向null
return newHead;//返回新的头节点
}
}
//O(n)
//O(n)
版权声明
本文为[[email protected]]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_43478694/article/details/125986802
边栏推荐
- pytest接口自动化测试框架 | pytest之fixture介绍
- 了解string类
- 【活动早知道】LiveVideoStack近期活动一览
- 【倒计时10天】腾讯云音视频专场即将见面,千元大奖等你来拿!
- 面试官:如何理解QPS,TPS,RT?
- Fineos announced the open registration of grouptech connect activities in 2022
- Esp8266 Arduino programming example - know esp8266
- 虚拟偶像代言产品出问题谁负责? 且听律师分析
- MongoDN数据库以URL形式连接
- 3.1 create menu and game page - up
猜你喜欢

初试YOLOv7

开放原子开源基金会OpenHarmony工作委员会主席侯培新寄语OpenAtom OpenHarmony分论坛

Is it easy to find a job after programmer training?

系统调用捕获和分—Ring3层LD_PRELOAD机制进行库函数劫持
![[download attached] a powerful web automated vulnerability scanning tool - Xray](/img/5e/1db72ce9bf758b1e68e8d6d2026302.png)
[download attached] a powerful web automated vulnerability scanning tool - Xray

Cohere博客:在生产环境中运行大型语言模型-推理框架概览

Mlx90640 infrared thermal imager temperature sensor module development notes (6)

线上一个隐匿 Bug 的复盘

What is per title encoding?

Hashtable
随机推荐
Koin
Modeling essay series 150 SCLC engineering experiment 3-srule
[cloud co creation] what good habits do you adhere to in order to write good code?
pytest接口自动化测试框架 | 使用装饰器修饰需要运行的用例
[ten thousand words long text] Based on LSM tree thought Net 6.0 C # realize kV database (case version)
Miccai2022 paper | evolutionary multi-objective architecture search framework: application in covid-19 3D CT classification
Sunflower senior product director technology sharing: how to apply in AD domain environment
系统调用捕获和分析完结篇制作系统调用日志收集系统
了解string类
虚拟偶像代言产品出问题谁负责? 且听律师分析
.....
Application scheme of ankerui residual pressure monitoring system in residential quarter
pytest接口自动化测试框架 | pytest之fixture介绍
Pytoch -- error based on mmseg/mmdet training: runtimeerror: expected to have finished reduction in the priority iteration
一些实用、常用、效率越来越高的 Kubernetes 别名
MongoDN数据库以URL形式连接
滴滴被罚80亿!拿用户数据赚钱的时代结束了
程序员培训学习后好找工作吗?
按位与怎么写SQL
Substance Painter 2021软件安装包下载及安装教程