当前位置:网站首页>LeetCode 练习——206. 反转链表
LeetCode 练习——206. 反转链表
2022-07-05 17:22:00 【SK_Jaco】
1.题目描述
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
2.解题思路与代码
2.1 解题思路
这道题比较简单,但是也是面试中非常常见的一道题目。题目要求反转链表,可以暴力使用栈解答,但是这样做不够精简在面市场上是得不到分的,并且需要两次遍历。因此使用三个引用变量 pre、next、curr 来指代上一个节点、下一个节点和当前节点。开始将 curr 指向 头节点并从头节点开始进行遍历,next 指向当前节点的下一个节点,然后让当前节点的 next 指向前一个节点,也就是 pre。再往后移动 pre 和 curr,使 pre 指向当前节点 curr ,当前节点 curr 后移指向 next。下面题目示例 1->2->3->4->5->NULL 进行图解:
- 首先 curr 指向头节点 1,pre 和 next 指向 null;
- 然后 next 指向 curr 的下一个节点 2;
- curr 的 next 指向 pre,并且 curr 后移指向 2;
- 重复上面步骤,直到 curr 指向 null,此时返回 pre 指向节点,即反转后的头节点

2.2 代码
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
ListNode pre = null;
ListNode next = null;
ListNode curr = head;
while (curr != null) {
next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}
return pre;
}
}
2.3 测试结果
通过测试

3.总结
- 这是链表中非常简单的应用,面试中常出现
- 使用 pre、curr、next 三个变量来完成反转,整个流程不难思路整理清楚即可
- 这道题与 剑指 Offer 24. 反转链表 相同
边栏推荐
- MySql 查询符合条件的最新数据行
- Kafaka technology lesson 1
- 漫画:寻找股票买入卖出的最佳时机
- 基于YOLOv3的口罩佩戴检测
- Design of electronic clock based on 51 single chip microcomputer
- Understand the usage of functions and methods in go language
- ICML 2022 | Meta propose une méthode robuste d'optimisation bayésienne Multi - objectifs pour faire face efficacement au bruit d'entrée
- What are the precautions for MySQL group by
- 排错-关于clion not found visual studio 的问题
- 十个顶级自动化和编排工具
猜你喜欢

Knowledge points of MySQL (7)
Example tutorial of SQL deduplication

7 pratiques devops pour améliorer la performance des applications

Oracle recovery tools -- Oracle database recovery tool

Which is more cost-effective, haqu K1 or haqu H1? Who is more worth starting with?

MySQL之知识点(六)

leetcode每日一练:旋转数组

mongodb(快速上手)(一)

每日一练:关于日期的一系列

33: Chapter 3: develop pass service: 16: use redis to cache user information; (to reduce the pressure on the database)
随机推荐
Winedt common shortcut key modify shortcut key latex compile button
漫画:有趣的海盗问题 (完整版)
较文心损失一点点性能提升很多
基于YOLOv3的口罩佩戴检测
IDEA 项目启动报错 Shorten the command line via JAR manifest or via a classpath file and rerun.
Flow characteristics of kitchen knife, ant sword, ice scorpion and Godzilla
Design of electronic clock based on 51 single chip microcomputer
Cartoon: how to multiply large integers? (next)
Cloud security daily 220705: the red hat PHP interpreter has found a vulnerability of executing arbitrary code, which needs to be upgraded as soon as possible
Troubleshooting - about clip not found Visual Studio
哈趣K1和哈趣H1哪个性价比更高?谁更值得入手?
查看自己电脑连接过的WiFi密码
Oracle缩表空间的完整解决实例
力扣解法汇总1200-最小绝对差
c#图文混合,以二进制方式写入数据库
How to modify MySQL fields as self growing fields
漫画:寻找无序数组的第k大元素(修订版)
读libco保存恢复现场汇编代码
忽米沄析:工业互联网标识解析与企业信息系统的融合应用
力扣解法汇总729-我的日程安排表 I