【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
相关推荐
0566464 小时前
agent学习Day15——SQLAlchemy 查询过滤、分页与历史列表接口
python·学习·fastapi
程序员爱德华6 小时前
Python与C++:异同点对比
c++·python
hangyuekejiGEO6 小时前
GEO技术服务选型指南
大数据·人工智能·python
普通攻击往后拉6 小时前
Leetcode 206. 反转链表
算法·leetcode·链表
软萌萌的16 小时前
Java Spring Boot 修改yml配置&加载顺序规则
java·spring boot·python
@syh.7 小时前
【贪心】矩阵消除游戏
算法·游戏·矩阵
可编程芯片开发7 小时前
基于零极点配置的PID控制系统simulink建模与仿真
算法
Dxy12393102167 小时前
Linux 编译安装 Python 3.12.10(多版本共存,不破坏系统Python)
linux·运维·python
徐小夕7 小时前
开源!我用SQLite + DuckDB打造了一款可视化AI问数平台
前端·算法·github