[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

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

相关推荐
grrrr_11 分钟前
【ctfplus】python靶场记录-任意文件读取+tornado模板注入+yaml反序列化(新手向)
python·web安全·tornado
瀚海澜生3 分钟前
链表系列入门指南(二):吃透这几题,链表解题不再难
后端·算法
爱编码的傅同学8 分钟前
数据结构(五)——AVL树(平衡二叉搜索树)
数据结构·算法
Bonnie_12159 分钟前
02-redis-数据结构实现原理
数据结构·redis·算法
ππ记录21 分钟前
python面试技巧
python·python面试·python面试技巧·python面试能力
Wood_Like30 分钟前
从递归入手一维动态规划
算法·动态规划
折枝寄北33 分钟前
数据结构 | 证明链表环结构是否存在
数据结构·链表
csdn_aspnet1 小时前
windows 安装 pygame( pycharm)
python·pycharm·pygame
这里有鱼汤1 小时前
Python自动化神器Playwright:让浏览器乖乖听话的终极指南!
后端·爬虫·python
海天一色y1 小时前
Pycharm(十三)容器类型的公共运算符和公共方法
ide·python·pycharm