【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
相关推荐
Arva .1 分钟前
G1收集器
java·jvm·算法
December3101 分钟前
【少儿编程】Scratch vs Python:区别、学习顺序&实操指南
python·学习·青少年编程·scratch·少儿编程·编程学习
努力毕业的小土博^_^2 分钟前
【生成式AI】Cross-Attention:多模态融合的神经网络桥梁(上篇)
人工智能·深度学习·神经网络·算法·机器学习·遥感
serve the people3 分钟前
tensorflow 如何使用 tf.RaggedTensorSpec 来创建 RaggedTensor
人工智能·python·tensorflow
larance3 分钟前
使用setuptools 打包python 模块
开发语言·python
速易达网络4 分钟前
Python全栈学习路径:从零基础到人工智能实战
python·flask
秋刀鱼 ..4 分钟前
2026生物神经网络与智能优化国际研讨会(BNNIO 2026)
大数据·python·计算机网络·数学建模·制造
龘龍龙11 分钟前
Python基础学习(二)
开发语言·python·学习
Generalzy14 分钟前
轻量级向量库chromadb
python
聆风吟º22 分钟前
【顺序表习题|图解|双指针】移除元素 + 删除有序数组中的重复项
c语言·数据结构·c++·经验分享·算法