【LeetCode】每日一题:反转链表

题解思路

循环的方法需要注意prev应该是None开始,然后到结束的时候prev是tail,递归的思路很难绕过弯来,主要在于很难想清楚为什么可以返回尾节点,需要多做递归题,以及递归过程中,可以不使用尾节点来找当前递归位置,用head结点即可,多用边界情况推理。

AC代码

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 head.next is None:
        #     return head
        # newhead = self.reverseList(head.next)
        # head.next.next = head
        # head.next = None
        # return newhead

        prev = None
        curr = head
        while curr:
            temp = curr.next
            curr.next = prev
            prev = curr
            curr = temp
        return prev
相关推荐
小北方城市网6 小时前
微服务注册中心与配置中心实战(Nacos 版):实现服务治理与配置统一
人工智能·后端·安全·职场和发展·wpf·restful
TracyCoder1236 小时前
Java String:从内存模型到不可变设计
java·算法·string
码农丁丁6 小时前
第二十七篇 技术管理者自身的能力升级
人工智能·职场和发展·技术管理·ai时代的技术管理
我是大咖6 小时前
二维数组与数组指针
java·数据结构·算法
筵陌6 小时前
算法:动态规划
算法·动态规划
大江东去浪淘尽千古风流人物6 小时前
【DSP】xiBoxFilter_3x3_U8 dsp VS cmodel
linux·运维·人工智能·算法·vr
长行6 小时前
Python|Windows 安装 DeepSpeed 安装方法及报错 Unable to pre-compile async_io 处理
windows·python·deepspeed
百锦再6 小时前
python之路并不一马平川:带你踩坑Pandas
开发语言·python·pandas·pip·requests·tools·mircro
Python之栈6 小时前
5款拖拽式Python GUI生成器助你快速打造炫酷界面
python
灏瀚星空6 小时前
基于 Python 与 GitHub,打造个人专属本地化思维导图工具全流程方案(上)
开发语言·人工智能·经验分享·笔记·python·个人开发·visual studio