反转链表(LeetCode)

题目

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

解题

python 复制代码
class ListNode:
    def __init__(self, value=0, next=None):
        self.value = value
        self.next = next


def reverse_linked_list_recursive(head: ListNode) -> ListNode:
    # 空链表或单节点链表
    if not head or not head.next:
        return head

    # 递归反转子链表
    new_head = reverse_linked_list_recursive(head.next)

    # 处理当前节点
    head.next.next = head
    head.next = None

    return new_head


# 辅助函数:创建链表
def create_linked_list(elements):
    if not elements:
        return None
    return ListNode(elements[0], create_linked_list(elements[1:]))


# 辅助函数:打印链表
def print_linked_list(head: ListNode):
    current = head
    while current:
        print(current.value, end=" -> " if current.next else "\n")
        current = current.next


# 测试代码
if __name__ == '__main__':
    # 创建链表: 1 -> 2 -> 3 -> 4 -> 5
    elements = [1, 2, 3, 4, 5]
    head = create_linked_list(elements)

    print("原始链表:")
    print_linked_list(head)

    reversed_head = reverse_linked_list_recursive(head)

    print("反转后的链表:")
    print_linked_list(reversed_head)

原始链表:

1 -> 2 -> 3 -> 4 -> 5

反转后的链表:

5 -> 4 -> 3 -> 2 -> 1

相关推荐
05候补工程师4 分钟前
从算法理想向工程现实的跨越:SLAM 核心架构、思维误区与 Nav2 实战避坑指南
人工智能·算法·安全·架构·机器人
深度先生20 分钟前
Conda 全面讲解——数据科学家的标配工具
python
深度先生36 分钟前
虚拟环境:别让包打架
python
漠效1 小时前
随机代理‌IP访问脚本
开发语言·python
SilentSamsara1 小时前
元类与 __init_subclass__:类是如何被“创建“出来的
开发语言·python·青少年编程
手写码匠1 小时前
Android 17 适配实战指南:新特性解读、隐私变更与迁移全攻略
人工智能·深度学习·算法·aigc
隔壁大炮1 小时前
MNE-Python 第6天学习笔记:分段(Epoching)与基线校正
python·eeg·mne·脑电数据处理
珊瑚里的鱼2 小时前
leetcode42雨水
算法·leetcode
SilentSamsara2 小时前
concurrent.futures 实战:进程池与线程池的统一抽象
运维·开发语言·python·青少年编程
不吃土豆的马铃薯2 小时前
Spdlog 进阶:日志基本控制、日志格式控制、异步记录器
linux·服务器·开发语言·前端·c++