【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
相关推荐
Daily Mirror几秒前
Day38 MLP神经网络的训练
python
代码游侠10 分钟前
学习笔记——线程控制 - 互斥与同步
linux·运维·笔记·学习·算法
yaoh.wang14 分钟前
力扣(LeetCode) 66: 加一 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
wanderist.36 分钟前
2025年蓝桥杯省赛C++大学A组
c++·算法·蓝桥杯
田姐姐tmner41 分钟前
Python 全面语法指南
开发语言·python
啊董dong1 小时前
noi-2025年12月16号作业
数据结构·c++·算法·noi
white-persist1 小时前
【攻防世界】reverse | simple-check-100 详细题解 WP
c语言·开发语言·汇编·数据结构·c++·python·算法
长安er1 小时前
LeetCode 01 背包 & 完全背包 题型总结
数据结构·算法·leetcode·动态规划·背包问题
王大傻09281 小时前
Series的属性简介
python·pandas
小南家的青蛙1 小时前
LeetCode第2658题 - 网格图中鱼的最大数目
算法·leetcode·职场和发展