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

相关推荐
葫三生1 小时前
如何评价《论三生原理》在科技界的地位?
人工智能·算法·机器学习·数学建模·量子计算
pipip.1 小时前
UDP————套接字socket
linux·网络·c++·网络协议·udp
拓端研究室3 小时前
视频讲解:门槛效应模型Threshold Effect分析数字金融指数与消费结构数据
前端·算法
朱包林4 小时前
day45-nginx复杂跳转与https
linux·运维·服务器·网络·云计算
孙克旭_4 小时前
day045-nginx跳转功能补充与https
linux·运维·nginx·https
随缘而动,随遇而安5 小时前
第八十八篇 大数据中的递归算法:从俄罗斯套娃到分布式计算的奇妙之旅
大数据·数据结构·算法
孞㐑¥5 小时前
Linux之Socket 编程 UDP
linux·服务器·c++·经验分享·笔记·网络协议·udp
郭庆汝5 小时前
pytorch、torchvision与python版本对应关系
人工智能·pytorch·python
IT古董5 小时前
【第二章:机器学习与神经网络概述】03.类算法理论与实践-(3)决策树分类器
神经网络·算法·机器学习
Alfred king8 小时前
面试150 生命游戏
leetcode·游戏·面试·数组