[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

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

相关推荐
江沉晚呤时5 小时前
在 C# 中调用 Python 脚本:实现跨语言功能集成
python·microsoft·c#·.net·.netcore·.net core
今天背单词了吗9806 小时前
算法学习笔记:19.牛顿迭代法——从原理到实战,涵盖 LeetCode 与考研 408 例题
笔记·学习·算法·牛顿迭代法
电脑能手6 小时前
如何远程访问在WSL运行的Jupyter Notebook
ide·python·jupyter
Edward-tan6 小时前
CCPD 车牌数据集提取标注,并转为标准 YOLO 格式
python
老胖闲聊7 小时前
Python I/O 库【输入输出】全面详解
开发语言·python
jdlxx_dongfangxing7 小时前
进制转换算法详解及应用
算法
倔强青铜三7 小时前
苦练Python第18天:Python异常处理锦囊
人工智能·python·面试
倔强青铜三7 小时前
苦练Python第17天:你必须掌握的Python内置函数
人工智能·python·面试
迷路爸爸1807 小时前
让 VSCode 调试器像 PyCharm 一样显示 Tensor Shape、变量形状、变量长度、维度信息
ide·vscode·python·pycharm·debug·调试
why技术8 小时前
也是出息了,业务代码里面也用上算法了。
java·后端·算法