[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

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

相关推荐
神仙别闹4 分钟前
基于Python实现LSTM对股票走势的预测
开发语言·python·lstm
机器学习之心34 分钟前
小波增强型KAN网络 + SHAP可解释性分析(Pytorch实现)
人工智能·pytorch·python·kan网络
JavaEdge在掘金40 分钟前
MySQL 8.0 的隐藏索引:索引管理的利器,还是性能陷阱?
python
站大爷IP1 小时前
Python办公自动化实战:手把手教你打造智能邮件发送工具
python
chao_7891 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
十盒半价1 小时前
从递归到动态规划:手把手教你玩转算法三剑客
javascript·算法·trae
GEEK零零七1 小时前
Leetcode 1070. 产品销售分析 III
sql·算法·leetcode
zdw1 小时前
fit parse解析佳明.fit 运动数据,模仿zwift数据展示
python
凌肖战2 小时前
力扣网编程274题:H指数之普通解法(中等)
算法·leetcode
秋说2 小时前
【PTA数据结构 | C语言版】将数组中元素反转存放
c语言·数据结构·算法