【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
相关推荐
写代码的【黑咖啡】几秒前
Python中的Statsmodels:统计建模与假设检验
开发语言·python
沉默-_-3 分钟前
力扣hot100双指针专题解析2(C++)
java·c++·算法·蓝桥杯·双指针
福楠5 分钟前
C++ | 红黑树
c语言·开发语言·数据结构·c++·算法
程序员杰哥5 分钟前
Pytest自动化测试框架实战
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
丝瓜蛋汤7 分钟前
Proof of the contraction mapping theorem
人工智能·算法
weixin_4331793313 分钟前
python - 函数 function
开发语言·python
We་ct26 分钟前
LeetCode 58. 最后一个单词的长度:两种解法深度剖析
前端·算法·leetcode·typescript
小袁顶风作案28 分钟前
leetcode力扣——452. 用最少数量的箭引爆气球
学习·算法·leetcode·职场和发展
deep_drink31 分钟前
【经典论文精读(一)】Isomap:非线性降维的全局几何框架(Science 2000)
人工智能·算法·机器学习
不吃鱼的小时喵41 分钟前
【Python】关于python多进程
python