LeetCode热题100-反转链表

python3实现

  • 循环方法:设置双指针,空间复杂度1,时间复杂度n
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]:
        cur, pre = head, None
        while cur:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        return pre

这里返回的pre,因为结束循环的条件为cur为空,当cur为空时,pre正好为表头。

  • 递归:注意递归设置的条件,第一次返回的表头
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]:
        def recur(cur, pre):
            if not cur:
                return pre
            res = recur(cur.next, cur)
            cur.next = pre
            return res
        
        return recur(head, None)
相关推荐
MageGojo几秒前
实时电影票房 API 接入实战:用 GET 请求获取影片票房榜单数据
python·电影票房·api 接口接入
菜菜的顾清寒1 分钟前
力扣HOT100(49)动态规划 -- 打家劫舍
算法·leetcode·动态规划
weixin_468466854 分钟前
Scrapling 高效网络爬虫实战指南
爬虫·python·编程·scrapling
yubo05096 分钟前
计算机视觉第十课:摄像头实时 颜色 + 形状 识别
python·opencv·计算机视觉
Dxy12393102167 分钟前
Django 三种 ENGINE 的区别
python·django·sqlite
Wang ruoxi7 分钟前
Pygame 小游戏——记忆方格
python·pygame
shuaiqinke9 分钟前
[Windows] 屏幕亮度调节工具
python
本地化文档13 分钟前
sphinxcontrib-rust-docs-l10n
python·rust·github·gitcode·sphinx
麻雀飞吧14 分钟前
2026年期货量化行情订阅层设计:主流平台Quote、K线与Tick取舍
python
眸生16 分钟前
基于NeteaseCloudMusicApi的音乐app 支持 DeepSeek 自然语言找歌、批量导入歌单、下载音乐转换成MP3,下载歌词
android·python·kotlin·android studio·音频·fastapi·android jetpack