【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
相关推荐
E_ICEBLUE13 小时前
Python 实现 PDF 表单域的自动化创建与智能填充
python·pdf·自动化·表单域
寻寻觅觅☆20 小时前
东华OJ-基础题-106-大整数相加(C++)
开发语言·c++·算法
YJlio20 小时前
1.7 通过 Sysinternals Live 在线运行工具:不下载也能用的“云端工具箱”
c语言·网络·python·数码相机·ios·django·iphone
偷吃的耗子20 小时前
【CNN算法理解】:三、AlexNet 训练模块(附代码)
深度学习·算法·cnn
l1t20 小时前
在wsl的python 3.14.3容器中使用databend包
开发语言·数据库·python·databend
化学在逃硬闯CS21 小时前
Leetcode1382. 将二叉搜索树变平衡
数据结构·算法
ceclar12321 小时前
C++使用format
开发语言·c++·算法
山塘小鱼儿21 小时前
本地Ollama+Agent+LangGraph+LangSmith运行
python·langchain·ollama·langgraph·langsimth
码说AI21 小时前
python快速绘制走势图对比曲线
开发语言·python