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

相关推荐
骑自行车的码农10 分钟前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了34 分钟前
AcWing学习——双指针算法
c++·算法
dessler1 小时前
Hadoop HDFS-高可用集群部署
linux·运维·hdfs
moonlifesudo1 小时前
322:零钱兑换(三种方法)
算法
泽泽爱旅行1 小时前
awk 语法解析-前端学习
linux·前端
这里有鱼汤2 小时前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩12 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在17 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
NAGNIP19 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
站大爷IP19 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python