当前位置:网站首页>链表(三)——反转链表
链表(三)——反转链表
2022-06-28 06:04:00 【木棣%】
给你单链表的头节点
head,请你反转链表,并返回反转后的链表示例 :

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
提示:
- 链表中节点的数目范围是 [0, 5000]
- -5000 <=
Node.val<= 5000
双指针
观察单链表的结构,只需要反转链表指针的指向
- 从头结点的位置开始改变指针指向
pre指向null,cur指向头结点- 将
cur的指向改为pre - 用
temp储存cur指向的下一个节点,便于下一次反转 curpre指向都后移一个位置,直至cur指向null
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode temp = null;
while (cur != null) {
temp = cur.next;// 保存下一个节点
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}
递归
在双指针中操作是重复的,也可以使用递归
- 确定好边界条件
class Solution {
public ListNode reverseList(ListNode head) {
// 初始化条件
return reverse(null, head);
}
public ListNode reverse(ListNode pre, ListNode cur) {
// 跳出递归的条件
if (cur == null) {
return pre;
}
ListNode temp = null;
temp = cur.next;// 先保存下一个节点
cur.next = pre;// 反转
return reverse(cur, temp); // 更新位置
}
}
边栏推荐
猜你喜欢

AutoCAD C# 多段线小锐角检测

Slow content advertising: the long-term principle of brand growth

Binder interview: memory management unit

Sklearn Feature Engineering (summary)

pytorch详解

5G网络整体架构

6. 毕业设计温湿度监控系统(ESP8266 + DHT11 +OLED 实时上传温湿度数据给公网服务器并在OLED显示屏上显示实时温湿度)

AutoCAD C# 多段线自相交检测

函数栈帧的创建和销毁

Lenovo hybrid cloud Lenovo xcloud, new enterprise IT service portal
随机推荐
The custom cube UI pop-up dialog supports multiple and multiple types of input boxes
High quality domestic stereo codec cjc8988, pin to pin replaces wm8988
Windows环境Redis使用AOF持久化,无法生成AOF文件,生成后无法加载AOF文件内容
idea创建类时自动添加注释
pytorch dataloader的长度 epoch与iteration的区别
[untitled]
Using pytorch and tensorflow to calculate the confusion matrix of classification model
Valueerror: iterative over raw text documents expected, string object received
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance
Ape pink ape power - Developer activity attack!
深度学习19种损失函数
Alibaba cloud SMS service (Complete Guide), SMS sending function implementation.
Apple MDM bypass jailfree bypass MDM configuration lock free
Simple handwritten debounce function
@Autowired注解为空的原因
安装 Ffmpefg
借助nz-pagination中的let-total解析ng-template
YYGH-6-微信登录
mysql常用函数
Academic search related papers