leetcode206. Reverse Linked List

Given the head of a singly linked list, reverse the list, and return the reversed list.

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
方法一:迭代(双指针)

考虑遍历链表,并在访问各节点时修改 next 引用指向

python 复制代码
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        cur, pre = head, None
        while cur:
            tmp = cur.next # 暂存后继节点 cur.next
            cur.next = pre # 修改 next 引用指向
            pre = cur      # pre 暂存 cur
            cur = tmp      # cur 访问下一节点
        return pre
python 复制代码
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        cur, pre = head, None
        while cur:
            cur.next, pre, cur = pre, cur, cur.next
        return pre

方法二:递归

考虑使用递归法遍历链表,当越过尾节点后终止递归,在回溯时修改各节点的 next 引用指向。

recur(cur, pre) 递归函数:

复制代码
终止条件:当 cur 为空,则返回尾节点 pre (即反转链表的头节点);
递归后继节点,记录返回值(即反转链表的头节点)为 res ;
修改当前节点 cur 引用指向前驱节点 pre ;
返回反转链表的头节点 res ;

reverseList(head) 函数:

调用并返回 recur(head, null) 。传入 null 是因为反转链表后, head 节点指向 null ;

python 复制代码
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        def recur(cur, pre):
            if not cur: return pre     # 终止条件
            res = recur(cur.next, cur) # 递归后继节点
            cur.next = pre             # 修改节点引用指向
            return res                 # 返回反转链表的头节点
        
        return recur(head, None)       # 调用递归并返回
相关推荐
你也向往长安城吗几秒前
推荐一个三维导航库:three-pathfinding-3d
javascript·算法
百度智能云17 分钟前
VectorDB+FastGPT一站式构建:智能知识库与企业级对话系统实战
算法
AI小白的Python之路1 小时前
数据结构与算法-排序
数据结构·算法·排序算法
DashVector1 小时前
如何通过Java SDK检索Doc
后端·算法·架构
zzz9331 小时前
transformer实战——mask
算法
一只鱼^_2 小时前
牛客周赛 Round 105
数据结构·c++·算法·均值算法·逻辑回归·动态规划·启发式算法
是阿建吖!2 小时前
【动态规划】斐波那契数列模型
算法·动态规划
啊阿狸不会拉杆2 小时前
《算法导论》第 27 章 - 多线程算法
java·jvm·c++·算法·图论
火车叨位去19492 小时前
力扣top100(day04-05)--堆
算法·leetcode·职场和发展
数据智能老司机2 小时前
面向企业的图学习扩展——面向图的传统机器学习
算法·机器学习