反转链表(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

相关推荐
点云SLAM16 分钟前
二叉树算法详解和C++代码示例
数据结构·c++·算法·红黑树·二叉树算法
李少兄2 小时前
CentOS系统下前后端项目部署攻略
linux·运维·centos
Two_brushes.5 小时前
【Linux】线程机制深度实践:创建、等待、互斥与同步
linux·运维·服务器·多线程
江沉晚呤时7 小时前
在 C# 中调用 Python 脚本:实现跨语言功能集成
python·microsoft·c#·.net·.netcore·.net core
设计师小聂!7 小时前
Linux系统中部署Redis详解
linux·运维·数据库·redis
kfepiza7 小时前
Debian-10编译安装Mysql-5.7.44 笔记250706
linux·数据库·笔记·mysql·debian·bash
今天背单词了吗9807 小时前
算法学习笔记:19.牛顿迭代法——从原理到实战,涵盖 LeetCode 与考研 408 例题
笔记·学习·算法·牛顿迭代法
没书读了7 小时前
考研复习-数据结构-第六章-图
数据结构
电脑能手7 小时前
如何远程访问在WSL运行的Jupyter Notebook
ide·python·jupyter
Edward-tan8 小时前
CCPD 车牌数据集提取标注,并转为标准 YOLO 格式
python