[LeetCode-Python版]206. 反转链表(迭代+递归两种解法)

题目

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例 1:

输入:head = 1,2,3,4,5

输出:5,4,3,2,1

示例 2:

输入:head = 1,2

输出:2,1

示例 3:

输入:head = \[\]

输出:\[\]

提示:

  • 链表中节点的数目范围是 0, 5000
  • -5000 <= Node.val <= 5000

题目链接

我的思路

定义cur指向当前节点,pre指向倒序链表,每次将当前节点的next指向pre
重点是每次要记录cur原来的next节点,否则就找不到了

我的代码

python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        pre = None
        cur = head

        while cur:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp 
        return pre

注意 :最后要返回pre而不是cur

题解思路

这道题还可以用递归做

把原问题转化成解决第一个节点怎么翻转的问题,不考虑里面的节点


递归过程:

  • head是我们要进行翻转的节点,head.next是已经翻转好的剩余节点
  • 那么只需要把剩余节点的next指向head,即head.next.next=head
  • 如果head是最后一个节点,那么要把head.next置为None

终止条件:如果只有一个节点,就返回那个节点

参考代码

python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head or not head.next: return head

        tmp = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return tmp
        

ps

链表类题目先画图理解再做题更好做

相关推荐
倒头就睡的小比特3 天前
算法竞赛C++常用的STL
c++·算法
默_笙3 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
qq_426003963 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫3 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技3 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
猎头南楼3 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
只睡四小时3 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
旖旎夜光3 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控