【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
相关推荐
yj155814 分钟前
新房子装修好不能直接入住的原因有哪些?
python
luoluoal15 分钟前
基于python的病人信息管理系统及安全策略分析(源码+文档)
python·mysql·django·毕业设计·源码
练习时长一年1 小时前
Leetcode热题100(跳跃游戏 II)
算法·leetcode·游戏
小白菜又菜7 小时前
Leetcode 3432. Count Partitions with Even Sum Difference
算法·leetcode
cnxy1887 小时前
围棋对弈Python程序开发完整指南:步骤1 - 棋盘基础框架搭建
开发语言·python
落叶,听雪8 小时前
河南建站系统哪个好
大数据·人工智能·python
wuhen_n8 小时前
LeetCode -- 15. 三数之和(中等)
前端·javascript·算法·leetcode
sin_hielo8 小时前
leetcode 2483
数据结构·算法·leetcode
极客小云9 小时前
【生物医学NLP信息抽取:药物识别、基因识别与化学物质实体识别教程与应用】
python·机器学习·nlp
南_山无梅落9 小时前
12.Python3函数基础:定义、调用与参数传递规则
python