[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

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

相关推荐
哆啦A梦的口袋呀6 分钟前
基于Python学习《Head First设计模式》第六章 命令模式
python·学习·设计模式
努力搬砖的咸鱼9 分钟前
从零开始搭建 Pytest 测试框架(Python 3.8 + PyCharm 版)
python·pycharm·pytest
Calvex11 分钟前
PyCharm集成Conda环境
python·pycharm·conda
一千柯橘23 分钟前
python 项目搭建(类比 node 来学习)
python
sduwcgg28 分钟前
python的numpy的MKL加速
开发语言·python·numpy
大模型真好玩29 分钟前
可视化神器WandB,大模型训练的必备工具!
人工智能·python·mcp
东方佑31 分钟前
使用 Python 自动化 Word 文档样式复制与内容生成
python·自动化·word
水蓝烟雨32 分钟前
[面试精选] 0094. 二叉树的中序遍历
算法·面试精选
钢铁男儿36 分钟前
Python 接口:从协议到抽象基 类(定义并使用一个抽象基类)
开发语言·python
超闻逸事38 分钟前
【题解】[UTPC2024] C.Card Deck
c++·算法