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

相关推荐
格鸰爱童话7 分钟前
向AI学习项目技能(六)
java·人工智能·spring boot·python·学习
悟空爬虫-彪哥12 分钟前
VRChat开发环境配置,零基础教程
python
渣渣馬12 分钟前
rk3588s的firfly的linux的sdk版本
linux·运维·服务器
数据知道21 分钟前
《 Claude Code源码分析与实践》专栏目录
python·ai·github·claude code·claw code
曲幽30 分钟前
FastAPI+Vue:文件分片上传+秒传+断点续传,这坑我帮你踩平了!
python·vue·upload·fastapi·web·blob·chunk·spark-md5
哎嗨人生公众号32 分钟前
手写求导公式,让轨迹优化性能飞升,150ms变成9ms
开发语言·c++·算法·机器人·自动驾驶
foundbug99935 分钟前
STM32 内部温度传感器测量程序(标准库函数版)
stm32·单片机·嵌入式硬件·算法
Hello.Reader36 分钟前
为什么学线性代数(一)
线性代数·算法·机器学习
_深海凉_43 分钟前
LeetCode热题100-找到字符串中所有字母异位词
算法·leetcode·职场和发展
lcj251144 分钟前
【C语言】数据在内存中的存储
c语言·数据结构