当前位置:网站首页>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. 反转链表 相同
边栏推荐
- Matery主题自定义(一)黑夜模式
- Size_t 是无符号的
- 漫画:有趣的【海盗】问题
- 排错-关于clion not found visual studio 的问题
- Read libco save and restore the on-site assembly code
- Cartoon: how to multiply large integers? (integrated version)
- Check the WiFi password connected to your computer
- 提高应用程序性能的7个DevOps实践
- Disorganized series
- Ordinary programmers look at the code, and top programmers look at the trend
猜你喜欢

Count the running time of PHP program and set the maximum running time of PHP

2022新版PMP考试有哪些变化?

查看自己电脑连接过的WiFi密码

flask接口响应中的中文乱码(unicode)处理

Winedt common shortcut key modify shortcut key latex compile button

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

十个顶级自动化和编排工具

Server configuration jupyter environment

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

Oracle Recovery Tools ----oracle数据库恢复利器
随机推荐
EPM相关
Cartoon: interesting pirate problem (full version)
Winedt common shortcut key modify shortcut key latex compile button
Compter le temps d'exécution du programme PHP et définir le temps d'exécution maximum de PHP
外盘黄金哪个平台正规安全,怎么辨别?
毫无章法系列
漫画:如何实现大整数相乘?(上) 修订版
This 17-year-old hacker genius cracked the first generation iPhone!
PMP认证需具备哪些条件啊?费用多少啊?
Understand the usage of functions and methods in go language
MySql 查询符合条件的最新数据行
漫画:寻找股票买入卖出的最佳时机
统计php程序运行时间及设置PHP最长运行时间
较文心损失一点点性能提升很多
mysql5.6解析JSON字符串方式(支持复杂的嵌套格式)
Cartoon: how to multiply large integers? (I) revised version
Why is all (()) true and any (()) false?
中国银河证券开户安全吗 开户后多久能买股票
Cartoon: how to multiply large integers? (integrated version)
ICML 2022 | meta proposes a robust multi-objective Bayesian optimization method to effectively deal with input noise