当前位置:网站首页>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. 反转链表 相同
边栏推荐
- mysql5.6解析JSON字符串方式(支持复杂的嵌套格式)
- Alpha conversion from gamma space to linner space under URP (II) -- multi alpha map superposition
- ICML 2022 | meta proposes a robust multi-objective Bayesian optimization method to effectively deal with input noise
- Independent development is a way out for programmers
- How MySQL uses JSON_ Extract() takes JSON value
- Is it safe for China Galaxy Securities to open an account? How long can I buy stocks after opening an account
- 华为云云原生容器综合竞争力,中国第一!
- 漫画:一道数学题引发的血案
- 论文阅读_中文NLP_LTP
- 漫画:有趣的海盗问题 (完整版)
猜你喜欢
神经网络自我认知模型
7. Scala class
What are the precautions for MySQL group by
漏洞复现----48、Airflow dag中的命令注入(CVE-2020-11978)
Example tutorial of SQL deduplication
Compter le temps d'exécution du programme PHP et définir le temps d'exécution maximum de PHP
CVPR 2022 best student paper: single image estimation object pose estimation in 3D space
提高應用程序性能的7個DevOps實踐
In depth understanding of redis memory obsolescence strategy
统计php程序运行时间及设置PHP最长运行时间
随机推荐
为什么阳历中平年二月是28天
Cartoon: a bloody case caused by a math problem
使用QT设计师界面类创建2个界面,通过按键从界面1切换到界面2
普通程序员看代码,顶级程序员看趋势
求解为啥all(())是True, 而any(())是FALSE?
mongodb(快速上手)(一)
解决“双击pdf文件,弹出”请安装evernote程序
QT控制台打印输出
Tita 绩效宝:如何为年中考核做准备?
WebApp开发-Google官方教程
7 pratiques devops pour améliorer la performance des applications
Beijing internal promotion | the machine learning group of Microsoft Research Asia recruits full-time researchers in nlp/ speech synthesis and other directions
Why is all (()) true and any (()) false?
IDEA 项目启动报错 Shorten the command line via JAR manifest or via a classpath file and rerun.
Vulnerability recurrence - 48. Command injection in airflow DAG (cve-2020-11978)
Flask solves the problem of CORS err
Design of electronic clock based on 51 single chip microcomputer
Read the history of it development in one breath
漫画:如何实现大整数相乘?(上) 修订版
This 17-year-old hacker genius cracked the first generation iPhone!