当前位置:网站首页>Sword finger offer 24. reverse the linked list
Sword finger offer 24. reverse the linked list
2022-07-26 12:37:00 【[email protected]】

Solution 1 : iteration
Use three variables ,pre Save the node at the end of the last traversal ,cur Save the currently traversed node ,next Save the next node
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)
Solution 2 : recursive
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null){
// The linked list is empty or only 1 Nodes
return head;
}
ListNode newHead=reverseList(head.next);// Reverse behind n-1 Nodes
head.next.next=head;// The original second 2 Nodes point to the old head node
head.next=null;// The old head node points to null
return newHead;// Return to the new header node
}
}
//O(n)
//O(n)
版权声明
本文为[[email protected]]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/207/202207261146342573.html
边栏推荐
- QT introduction and case explanation
- 三维点云课程(八)——特征点匹配
- Detailed interpretation of hole convolution (input and output size analysis)
- 腾讯云与智慧产业事业群(CSIG)调整组织架构,成立数字孪生产品部
- Codepoint 58880 not found in font, aborting. Flutter build APK reports an error
- QT入门引导 及其 案例讲解
- [map] universal map usage & two ways of fuzzy query
- FPGA入门学习(一) - 第一个FPGA工程
- 回溯——第51题. N皇后——必须攻克的经典回溯难题
- Access数据库无法连接
猜你喜欢

El form displays two columns per row, with the bottom button centered

FPGA入门学习(一) - 第一个FPGA工程

若有声明”int x=5,y=1;”,则表达式x<y?x++:y++的结果是:

Microsoft has shut down two attack methods: Office macro and RDP brute force cracking

回溯——46. 全排列

Redis master-slave replication principle

Introduction to FPGA (I) - the first FPGA project

2022 年要了解的新兴安全供应商

LCD笔记(7)LCD驱动程序框架_配置时钟

二、容器_
随机推荐
实体映射最强工具类:MapStruct真香
10. 509. Introduction to PKCs file format
The.Net webapi uses groupname to group controllers to render the swagger UI
详解勒让德变换与共轭函数
数据库组成存储过程和函数
MySQL之数据查询(聚合函数)
Oracle AWR report script: SQL ordered by elapsed time
Minesweeping games - easy to play addictive (C language version)
Pytoch deep learning quick start tutorial -- mound tutorial notes (II)
X.509、PKCS文件格式介绍
Ubenwa, a start-up under Mila, received an investment of US $2.5 million to study the AI diagnosis of infant health
三维点云课程(八)——特征点匹配
虚拟偶像代言产品出问题谁负责?且听律师分析
什么是回调函数,对于“回”字的理解
回溯——第51题. N皇后——必须攻克的经典回溯难题
Codepoint 58880 not found in font, aborting. Flutter build APK reports an error
[MySQL constraint]
“2022华为开发者大赛中国区东部赛区开幕式”在福州成功举办
Introduction to FPGA (I) - the first FPGA project
【2243】module_ param.m