力扣热题100之反转链表

题目

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

代码

方法一:

重点需要理解的是正确翻转的流程:在链表未被破坏之前保留cur的下一个节点信息->改变cur.next的指向->更新prev的位置->更新cur

bash 复制代码
# 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]:           
        cur=head   
        prev=None 
        while cur:
            Next=cur.next # 首先应该保存下一个节点
            cur.next=prev # 然后翻转
            prev=cur # 然后更新pre
            cur=Next # 然后将cur指向没有被改变的下一个节点
        return prev  # 返回翻转之后的链表的头节点    

方法二:递归

主要在于理解什么是递归,递归是怎么运行的,之前上课的时候老师说的一个比喻就是:递归就向打开一扇扇门,到最后一扇之后又从最后一扇门开始关门。也就是说这个代码中就是先反复调用reverseList函数到链表的最后一个元素(满足结束条件),执行head.next.next=head, head.next=None这两句代码,然后轮到倒数第二个元素进行上述操作......

假设原链表:1 -> 2 -> 3 -> 4 -> 5

递归过程:

  1. 递归至节点5,返回5。
  2. 节点4处理:5->4->None。
  3. 节点3处理:5->4->3->None。
  4. 节点2处理:5->4->3->2->None。
  5. 节点1处理:5->4->3->2->1->None。
    最终链表:5 ->4 ->3 ->2 ->1
bash 复制代码
# 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 head==None or head.next==None:
            return head
        new_head=self.reverseList(head.next)
        head.next.next=head
        head.next=None
        return new_head
相关推荐
dulu~dulu4 分钟前
算法---寻找和为K的子数组
笔记·python·算法·leetcode
moonsea020315 分钟前
【无标题】
算法
佑白雪乐36 分钟前
<ACM进度212题>[2026-3-1,2026-3-26]
算法·leetcode
穿条秋裤到处跑39 分钟前
每日一道leetcode(2026.03.26):等和矩阵分割 II
算法·leetcode·矩阵
平凡灵感码头43 分钟前
C语言 printf 数据打印格式速查表
c语言·开发语言·算法
哔哔龙1 小时前
Android OpenCV 实战:图片轮廓提取与重叠轮廓合并处理
android·算法
hz_zhangrl1 小时前
CCF-GESP 等级考试 2026年3月认证C++三级真题解析
c++·算法·程序设计·gesp·gesp2026年3月·gesp c++三级
x_xbx1 小时前
LeetCode:1. 两数之和
数据结构·算法·leetcode
x_xbx1 小时前
LeetCode:49. 字母异位词分组
算法·leetcode·职场和发展
玲娜贝儿--努力学习买大鸡腿版1 小时前
hot 100 刷题记录(1)
数据结构·python·算法