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)       # 调用递归并返回
相关推荐
ZZZS05165 分钟前
stack栈练习
c++·笔记·学习·算法·动态规划
hans汉斯30 分钟前
【人工智能与机器人研究】基于力传感器坐标系预标定的重力补偿算法
人工智能·算法·机器人·信号处理·深度神经网络
vortex52 小时前
算法设计与分析:分治、动态规划与贪心算法的异同与选择
算法·贪心算法·动态规划
前端拿破轮2 小时前
🤡🤡🤡面试官:就你这还每天刷leetcode?连四数相加和四数之和都分不清!
算法·leetcode·面试
地平线开发者3 小时前
征程 6|工具链量化简介与代码实操
算法·自动驾驶
DoraBigHead3 小时前
🧠 小哆啦解题记——谁偷改了狗狗的台词?
算法
Kaltistss3 小时前
240.搜索二维矩阵Ⅱ
线性代数·算法·矩阵
轻语呢喃3 小时前
每日LeetCode:合并两个有序数组
javascript·算法
大熊猫侯佩4 小时前
Swift 数学计算:用 Accelerate 框架让性能“加速吃鸡”
算法·swift
杰克尼4 小时前
2. 两数相加
算法