力扣热题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
相关推荐
夏幻灵2 小时前
每日一题:LeetCode 3:无重复字符的最长子串——滑动窗口思路详解
算法·leetcode·职场和发展
CarIise3 小时前
Java实训阶段查漏补缺复习笔记2
java·linux·算法
无忧.芙桃3 小时前
C++ 并查集详解:原理、实现与应用
c语言·c++·算法·leetcode
蛋蛋的就会顺顺的3 小时前
hot100——二叉树
java·数据结构·算法·leetcode·力扣
Code_Solitude4 小时前
c语言:二分法的完整补充
c语言·开发语言·算法
一切皆是因缘际会4 小时前
掌控信息论:同源星际通信基础理论
人工智能·算法·ai
List<String> error_P5 小时前
freertos数据结构--链表
数据结构·链表
动词ing6 小时前
【C语言题目练习】算法 整数反转
c语言·开发语言·算法
Nil2086 小时前
leetcode 55跳跃游戏
算法·leetcode·游戏
longlongzihan6 小时前
LeetCode 128. 最长连续序列 —— 从排序到哈希集合
数据结构·c++·算法·leetcode·排序算法·哈希表