【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
相关推荐
C雨后彩虹7 分钟前
竖直四子棋
java·数据结构·算法·华为·面试
Lxinccode18 分钟前
BUG(20) : response.text耗时很久, linux耗时十几秒, Windows耗时零点几秒
python·bug·requests·response.text·response.text慢
智航GIS22 分钟前
11.2 Matplotlib 数据可视化教程
python·信息可视化·matplotlib
技术净胜26 分钟前
Python 操作 Cookie 完全指南,爬虫与 Web 开发实战
前端·爬虫·python
海棠AI实验室31 分钟前
第六章 日志体系:logging 让排错效率翻倍
python·logging
laufing38 分钟前
flask_restx 创建restful api
python·flask·restful
不如自挂东南吱1 小时前
空间相关性 和 怎么捕捉空间相关性
人工智能·深度学习·算法·机器学习·时序数据库
洛生&1 小时前
Elevator Rides
算法
2501_933513041 小时前
关于一种计数的讨论、ARC212C Solution
算法